blob: 1df0ff23f8477d042e152d17a492d4abef145f9d [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
53import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000054import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.app.admin.DeviceAdminReceiver;
56import android.app.admin.DevicePolicyManager;
57import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010058import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000062import android.content.pm.ApplicationInfo;
63import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010065import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000066import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010068import android.graphics.Color;
69import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080070import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080071import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080073import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070075import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010076import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080077import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010078import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000079import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000080import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080081import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000082import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010083import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000087import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000088import com.android.server.LocalServices;
89import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000090import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000091import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000092
Robin Lee7f5c91c2017-02-08 21:27:02 +000093import org.hamcrest.BaseMatcher;
94import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080095import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import org.mockito.invocation.InvocationOnMock;
97import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
Makoto Onukic8a5a552015-11-19 14:29:12 -080099import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000101import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700102import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700104import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100105import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000106import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700109 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000110 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 m FrameworksServicesTests &&
112 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000113 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800115 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116
117 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000118 *
119 * , or:
120 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000122@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100123@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000125 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
126 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
127 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100128 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
129 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000130
Pavel Grafov75c0a892017-05-18 17:28:27 +0100131 // TODO replace all instances of this with explicit {@link #mServiceContext}.
132 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100134
135 private DpmMockContext mServiceContext;
136 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700137 public DevicePolicyManager dpm;
138 public DevicePolicyManagerServiceTestable dpms;
139
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100140 /*
141 * The CA cert below is the content of cacert.pem as generated by:
142 *
143 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
144 */
145 private static final String TEST_CA =
146 "-----BEGIN CERTIFICATE-----\n" +
147 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
148 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
149 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
150 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
151 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
152 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
153 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
154 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
155 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
156 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
157 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
158 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
159 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
160 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
161 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
162 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
163 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
164 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
165 "wQ==\n" +
166 "-----END CERTIFICATE-----\n";
167
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700168 @Override
169 protected void setUp() throws Exception {
170 super.setUp();
171
172 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100173 mServiceContext = mContext;
174 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
175 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700176 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100177 doReturn(Collections.singletonList(new ResolveInfo()))
178 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
179 any(Intent.class),
180 anyInt(),
181 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700182
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800183 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100184 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800185
Makoto Onukia52562c2015-10-01 16:12:31 -0700186 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700187
Sudheer Shanka101c3532018-01-08 16:28:42 -0800188 Mockito.reset(getServices().usageStatsManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700189 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
190 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
191 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800192 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700193
Pavel Grafov75c0a892017-05-18 17:28:27 +0100194 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
195 mAdmin1Context.packageName = admin1.getPackageName();
196 mAdmin1Context.applicationInfo = new ApplicationInfo();
197 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
198
Makoto Onukib643fb02015-09-22 15:03:44 -0700199 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700200 }
201
Robin Lee2c68dad2017-03-17 12:50:24 +0000202 @Override
203 protected void tearDown() throws Exception {
204 flushTasks();
205 super.tearDown();
206 }
207
Makoto Onukia52562c2015-10-01 16:12:31 -0700208 private void initializeDpms() {
209 // Need clearCallingIdentity() to pass permission checks.
210 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100211 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700212
Pavel Grafov75c0a892017-05-18 17:28:27 +0100213 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
Sudheer Shanka101c3532018-01-08 16:28:42 -0800214 dpms.handleStart();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100215 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
216 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700217
Pavel Grafov75c0a892017-05-18 17:28:27 +0100218 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700219
Pavel Grafov75c0a892017-05-18 17:28:27 +0100220 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700221 }
222
Makoto Onukib643fb02015-09-22 15:03:44 -0700223 private void setUpUserManager() {
224 // Emulate UserManager.set/getApplicationRestriction().
225 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
226
227 // UM.setApplicationRestrictions() will save to appRestrictions.
228 doAnswer(new Answer<Void>() {
229 @Override
230 public Void answer(InvocationOnMock invocation) throws Throwable {
231 String pkg = (String) invocation.getArguments()[0];
232 Bundle bundle = (Bundle) invocation.getArguments()[1];
233 UserHandle user = (UserHandle) invocation.getArguments()[2];
234
235 appRestrictions.put(Pair.create(pkg, user), bundle);
236
237 return null;
238 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100240 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700241
242 // UM.getApplicationRestrictions() will read from appRestrictions.
243 doAnswer(new Answer<Bundle>() {
244 @Override
245 public Bundle answer(InvocationOnMock invocation) throws Throwable {
246 String pkg = (String) invocation.getArguments()[0];
247 UserHandle user = (UserHandle) invocation.getArguments()[1];
248
249 return appRestrictions.get(Pair.create(pkg, user));
250 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100251 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700252 anyString(), any(UserHandle.class));
253
Makoto Onukid932f762015-09-29 16:53:38 -0700254 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100255 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700256 }
257
258 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100259 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700260
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 mServiceContext.binder.callingUid =
262 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
263 runAsCaller(mServiceContext, dpms, dpm -> {
264 // PO needs to be a DA.
265 dpm.setActiveAdmin(admin, /*replace=*/ false);
266 // Fire!
267 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
268 // Check
269 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
270 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700271
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700273 }
274
275 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100276 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700277 .thenReturn(false);
278
279 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100280 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700281
282 // If the device has no DPMS feature, it shouldn't register the local service.
283 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
284 }
285
Sudheer Shanka101c3532018-01-08 16:28:42 -0800286 public void testHandleStart() throws Exception {
287 // Device owner in SYSTEM_USER
288 setDeviceOwner();
289 // Profile owner in CALLER_USER_HANDLE
290 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
291 setAsProfileOwner(admin2);
292 // Active admin in CALLER_USER_HANDLE
293 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
294 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
295 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
296 DpmMockContext.CALLER_USER_HANDLE);
297 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
298 DpmMockContext.CALLER_USER_HANDLE));
299
300 initializeDpms();
301
302 // Verify
303 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
304 MockUtils.checkAdminApps(admin1.getPackageName()),
305 eq(UserHandle.USER_SYSTEM));
306 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
307 MockUtils.checkAdminApps(admin2.getPackageName(),
308 adminAnotherPackage.getPackageName()),
309 eq(DpmMockContext.CALLER_USER_HANDLE));
310 }
311
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700312 /**
313 * Caller doesn't have proper permissions.
314 */
315 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700316 // 1. Failure cases.
317
318 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100319 assertExpectException(SecurityException.class, /* messageRegex= */ null,
320 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700321
322 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
323 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100324
325 assertExpectException(SecurityException.class, /* messageRegex= */ null,
326 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700327 }
328
Makoto Onukif76b06a2015-09-22 15:03:44 -0700329 /**
330 * Test for:
331 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800332 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700333 * {@link DevicePolicyManager#isAdminActive}
334 * {@link DevicePolicyManager#isAdminActiveAsUser}
335 * {@link DevicePolicyManager#getActiveAdmins}
336 * {@link DevicePolicyManager#getActiveAdminsAsUser}
337 */
338 public void testSetActiveAdmin() throws Exception {
339 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700340 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
341
Makoto Onukif76b06a2015-09-22 15:03:44 -0700342 // 2. Call the API.
343 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344
345 // 3. Verify internal calls.
346
347 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700348 verify(mContext.spiedContext).sendBroadcastAsUser(
349 MockUtils.checkIntentAction(
350 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
351 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
352 verify(mContext.spiedContext).sendBroadcastAsUser(
353 MockUtils.checkIntentAction(
354 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700355 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
356
Pavel Grafov75c0a892017-05-18 17:28:27 +0100357 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700358 eq(admin1.getPackageName()),
359 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
360 eq(PackageManager.DONT_KILL_APP),
361 eq(DpmMockContext.CALLER_USER_HANDLE),
362 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700363
Sudheer Shanka101c3532018-01-08 16:28:42 -0800364 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
365 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
366
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700367 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700368
369 // Make sure it's active admin1.
370 assertTrue(dpm.isAdminActive(admin1));
371 assertFalse(dpm.isAdminActive(admin2));
372 assertFalse(dpm.isAdminActive(admin3));
373
374 // But not admin1 for a different user.
375
376 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
377 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
378 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
379
380 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
381 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
382
383 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
384
385 // Next, add one more admin.
386 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700387 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700388 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389
390 dpm.setActiveAdmin(admin2, /* replace =*/ false);
391
392 // Now we have two admins.
393 assertTrue(dpm.isAdminActive(admin1));
394 assertTrue(dpm.isAdminActive(admin2));
395 assertFalse(dpm.isAdminActive(admin3));
396
397 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
398 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100399 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700400 eq(admin1.getPackageName()),
401 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
402 eq(PackageManager.DONT_KILL_APP),
403 eq(DpmMockContext.CALLER_USER_HANDLE),
404 anyString());
405
Sudheer Shanka101c3532018-01-08 16:28:42 -0800406 // times(2) because it was previously called for admin1 which is in the same package
407 // as admin2.
408 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
409 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
410
Makoto Onukif76b06a2015-09-22 15:03:44 -0700411 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100412 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
413 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700414
415 // 5. Add the same admin1 again with replace, which should succeed.
416 dpm.setActiveAdmin(admin1, /* replace =*/ true);
417
418 // TODO make sure it's replaced.
419
420 // 6. Test getActiveAdmins()
421 List<ComponentName> admins = dpm.getActiveAdmins();
422 assertEquals(2, admins.size());
423 assertEquals(admin1, admins.get(0));
424 assertEquals(admin2, admins.get(1));
425
Sudheer Shanka101c3532018-01-08 16:28:42 -0800426 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
427 // replaced
428 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
429
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 // Another user has no admins.
431 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
432
433 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
434 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
435
436 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
437 }
438
Makoto Onukid932f762015-09-29 16:53:38 -0700439 public void testSetActiveAdmin_multiUsers() throws Exception {
440
441 final int ANOTHER_USER_ID = 100;
442 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
443
Pavel Grafov75c0a892017-05-18 17:28:27 +0100444 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700445
446 // Set up pacakge manager for the other user.
447 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700448
449 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
450
451 dpm.setActiveAdmin(admin1, /* replace =*/ false);
452
453 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
454 dpm.setActiveAdmin(admin2, /* replace =*/ false);
455
456
457 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
458 assertTrue(dpm.isAdminActive(admin1));
459 assertFalse(dpm.isAdminActive(admin2));
460
461 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
462 assertFalse(dpm.isAdminActive(admin1));
463 assertTrue(dpm.isAdminActive(admin2));
464 }
465
Makoto Onukif76b06a2015-09-22 15:03:44 -0700466 /**
467 * Test for:
468 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800469 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700470 */
471 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
472 // 1. Make sure the caller has proper permissions.
473 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
474
475 dpm.setActiveAdmin(admin1, /* replace =*/ false);
476 assertTrue(dpm.isAdminActive(admin1));
477
478 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100479 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
480 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700481 }
482
483 /**
484 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800485 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
486 * BIND_DEVICE_ADMIN.
487 */
488 public void testSetActiveAdmin_permissionCheck() throws Exception {
489 // 1. Make sure the caller has proper permissions.
490 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
491
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100492 assertExpectException(IllegalArgumentException.class,
493 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
494 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800495 assertFalse(dpm.isAdminActive(adminNoPerm));
496
497 // Change the target API level to MNC. Now it can be set as DA.
498 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
499 VERSION_CODES.M);
500 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
501 assertTrue(dpm.isAdminActive(adminNoPerm));
502
503 // TODO Test the "load from the file" case where DA will still be loaded even without
504 // BIND_DEVICE_ADMIN and target API is N.
505 }
506
507 /**
508 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700509 * {@link DevicePolicyManager#removeActiveAdmin}
510 */
511 public void testRemoveActiveAdmin_SecurityException() {
512 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
513
514 // Add admin.
515
516 dpm.setActiveAdmin(admin1, /* replace =*/ false);
517
518 assertTrue(dpm.isAdminActive(admin1));
519
520 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
521
522 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
524 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525
526 // Try to remove active admin with a different caller userid should fail too, without
527 // having MANAGE_DEVICE_ADMINS.
528 mContext.callerPermissions.clear();
529
Makoto Onukid932f762015-09-29 16:53:38 -0700530 // Change the caller, and call into DPMS directly with a different user-id.
531
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100533 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
534 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 }
536
537 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800538 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
539 * (because we can't send the remove broadcast).
540 */
541 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
542 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
543
544 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
545
546 // Add admin.
547
548 dpm.setActiveAdmin(admin1, /* replace =*/ false);
549
550 assertTrue(dpm.isAdminActive(admin1));
551
552 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
553
554 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100555 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800556 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100557 assertExpectException(IllegalStateException.class,
558 /* messageRegex= */ "User must be running and unlocked",
559 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800560
561 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800562 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
563 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800564
565 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100566 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800567 .thenReturn(true);
568
569 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700570 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800571 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
572 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800573 }
574
575 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700576 * Test for:
577 * {@link DevicePolicyManager#removeActiveAdmin}
578 */
Makoto Onukid932f762015-09-29 16:53:38 -0700579 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700580 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
581
582 // Add admin1.
583
584 dpm.setActiveAdmin(admin1, /* replace =*/ false);
585
586 assertTrue(dpm.isAdminActive(admin1));
587 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
588
589 // Different user, but should work, because caller has proper permissions.
590 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700591
592 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700593 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700594
595 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700596 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800597 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
598 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700599
600 // TODO DO Still can't be removed in this case.
601 }
602
603 /**
604 * Test for:
605 * {@link DevicePolicyManager#removeActiveAdmin}
606 */
607 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
608 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
609 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
610
611 // Add admin1.
612
613 dpm.setActiveAdmin(admin1, /* replace =*/ false);
614
615 assertTrue(dpm.isAdminActive(admin1));
616 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
617
618 // Broadcast from saveSettingsLocked().
619 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
620 MockUtils.checkIntentAction(
621 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
622 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
623
624 // Remove. No permissions, but same user, so it'll work.
625 mContext.callerPermissions.clear();
626 dpm.removeActiveAdmin(admin1);
627
Makoto Onukif76b06a2015-09-22 15:03:44 -0700628 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
629 MockUtils.checkIntentAction(
630 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
631 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
632 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700633 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700634 eq(dpms.mHandler),
635 eq(Activity.RESULT_OK),
636 isNull(String.class),
637 isNull(Bundle.class));
638
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700639 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800640 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
641 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700642
643 // Again broadcast from saveSettingsLocked().
644 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
645 MockUtils.checkIntentAction(
646 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
647 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
648
649 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700650 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700651
Sudheer Shanka101c3532018-01-08 16:28:42 -0800652 public void testRemoveActiveAdmin_multipleAdminsInUser() {
653 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
654 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
655
656 // Add admin1.
657 dpm.setActiveAdmin(admin1, /* replace =*/ false);
658
659 assertTrue(dpm.isAdminActive(admin1));
660 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
661
662 // Add admin2.
663 dpm.setActiveAdmin(admin2, /* replace =*/ false);
664
665 assertTrue(dpm.isAdminActive(admin2));
666 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
667
668 // Broadcast from saveSettingsLocked().
669 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
670 MockUtils.checkIntentAction(
671 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
672 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
673
674 // Remove. No permissions, but same user, so it'll work.
675 mContext.callerPermissions.clear();
676 dpm.removeActiveAdmin(admin1);
677
678 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
679 MockUtils.checkIntentAction(
680 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
681 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
682 isNull(String.class),
683 any(BroadcastReceiver.class),
684 eq(dpms.mHandler),
685 eq(Activity.RESULT_OK),
686 isNull(String.class),
687 isNull(Bundle.class));
688
689 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
690 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
691 MockUtils.checkAdminApps(admin2.getPackageName()),
692 eq(DpmMockContext.CALLER_USER_HANDLE));
693
694 // Again broadcast from saveSettingsLocked().
695 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
696 MockUtils.checkIntentAction(
697 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
698 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
699 }
700
701 /**
702 * Test for:
703 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
704 */
705 public void testForceRemoveActiveAdmin() throws Exception {
706 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
707
708 // Add admin.
709 setupPackageInPackageManager(admin1.getPackageName(),
710 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
711 /* appId= */ 10138,
712 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
713 dpm.setActiveAdmin(admin1, /* replace =*/ false);
714 assertTrue(dpm.isAdminActive(admin1));
715
716 // Calling from a non-shell uid should fail with a SecurityException
717 mContext.binder.callingUid = 123456;
718 assertExpectException(SecurityException.class,
719 /* messageRegex =*/ "Non-shell user attempted to call",
720 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
721
722 mContext.binder.callingUid = Process.SHELL_UID;
723 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
724
725 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
726 // Verify
727 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
728 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
729 null, DpmMockContext.CALLER_USER_HANDLE);
730 }
731
Makoto Onukib643fb02015-09-22 15:03:44 -0700732 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000733 * Test for: @{link DevicePolicyManager#setActivePasswordState}
734 *
735 * Validates that when the password for a user changes, the notification broadcast intent
736 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
737 * addition to ones in the original user.
738 */
739 public void testSetActivePasswordState_sendToProfiles() throws Exception {
740 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
741
742 final int MANAGED_PROFILE_USER_ID = 78;
743 final int MANAGED_PROFILE_ADMIN_UID =
744 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
745
746 // Setup device owner.
747 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
748 mContext.packageName = admin1.getPackageName();
749 setupDeviceOwner();
750
751 // Add a managed profile belonging to the system user.
752 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
753
754 // Change the parent user's password.
755 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
756
757 // Both the device owner and the managed profile owner should receive this broadcast.
758 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
759 intent.setComponent(admin1);
760 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
761
762 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
763 MockUtils.checkIntent(intent),
764 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
765 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
766 MockUtils.checkIntent(intent),
767 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
768 }
769
770 /**
771 * Test for: @{link DevicePolicyManager#setActivePasswordState}
772 *
773 * Validates that when the password for a managed profile changes, the notification broadcast
774 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
775 * its parent.
776 */
777 public void testSetActivePasswordState_notSentToParent() throws Exception {
778 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
779
780 final int MANAGED_PROFILE_USER_ID = 78;
781 final int MANAGED_PROFILE_ADMIN_UID =
782 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
783
784 // Setup device owner.
785 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
786 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100787 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000788 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
789 setupDeviceOwner();
790
791 // Add a managed profile belonging to the system user.
792 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
793
794 // Change the profile's password.
795 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
796
797 // Both the device owner and the managed profile owner should receive this broadcast.
798 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
799 intent.setComponent(admin1);
800 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
801
802 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
803 MockUtils.checkIntent(intent),
804 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
805 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
806 MockUtils.checkIntent(intent),
807 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
808 }
809 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000810 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700811 */
812 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000813 setDeviceOwner();
814
815 // Try to set a profile owner on the same user, which should fail.
816 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
817 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100818 assertExpectException(IllegalStateException.class,
819 /* messageRegex= */ "already has a device owner",
820 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000821
822 // DO admin can't be deactivated.
823 dpm.removeActiveAdmin(admin1);
824 assertTrue(dpm.isAdminActive(admin1));
825
826 // TODO Test getDeviceOwnerName() too. To do so, we need to change
827 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
828 }
829
830 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700831 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800832 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700833 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
834 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
835
Makoto Onukid932f762015-09-29 16:53:38 -0700836 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700837 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
838
Makoto Onukid932f762015-09-29 16:53:38 -0700839 // Make sure admin1 is installed on system user.
840 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700841
Makoto Onukic8a5a552015-11-19 14:29:12 -0800842 // Check various get APIs.
843 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
844
Makoto Onukib643fb02015-09-22 15:03:44 -0700845 // DO needs to be an DA.
846 dpm.setActiveAdmin(admin1, /* replace =*/ false);
847
848 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700849 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700850
Makoto Onukic8a5a552015-11-19 14:29:12 -0800851 // getDeviceOwnerComponent should return the admin1 component.
852 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
853 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
854
855 // Check various get APIs.
856 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
857
858 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
859 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
860 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
861 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
862
863 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
864
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000865 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100866 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000867 eq(admin1.getPackageName()));
868
Makoto Onukib643fb02015-09-22 15:03:44 -0700869 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100870 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 eq(UserHandle.USER_SYSTEM), eq(false));
872
873 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
874 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
875 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
876
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 }
879
Makoto Onukic8a5a552015-11-19 14:29:12 -0800880 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
881 final int origCallingUser = mContext.binder.callingUid;
882 final List origPermissions = new ArrayList(mContext.callerPermissions);
883 mContext.callerPermissions.clear();
884
885 mContext.callerPermissions.add(permission.MANAGE_USERS);
886
887 mContext.binder.callingUid = Process.SYSTEM_UID;
888
889 // TODO Test getDeviceOwnerName() too. To do so, we need to change
890 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
891 if (hasDeviceOwner) {
892 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
893 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
894 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
895
896 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
897 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
898 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
899 } else {
900 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
901 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
902 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
903
904 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
905 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
906 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
907 }
908
909 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
910 if (hasDeviceOwner) {
911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
912 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
913 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
914
915 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
916 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
917 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
918 } else {
919 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
920 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
921 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
922
923 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
924 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
925 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
926 }
927
928 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
929 // Still with MANAGE_USERS.
930 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
931 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
932 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
933
934 if (hasDeviceOwner) {
935 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
936 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
937 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
938 } else {
939 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
940 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
941 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
942 }
943
944 mContext.binder.callingUid = Process.SYSTEM_UID;
945 mContext.callerPermissions.remove(permission.MANAGE_USERS);
946 // System can still call "OnAnyUser" without MANAGE_USERS.
947 if (hasDeviceOwner) {
948 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
949 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
950 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
951
952 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
953 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
954 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
955 } else {
956 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
957 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
958 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
959
960 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
961 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
962 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
963 }
964
965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
966 // Still no MANAGE_USERS.
967 if (hasDeviceOwner) {
968 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
969 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
970 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
971 } else {
972 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
973 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
974 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
975 }
976
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100977 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
978 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
980 dpm::getDeviceOwnerComponentOnAnyUser);
981 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
982 dpm::getDeviceOwnerUserId);
983 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
984 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800985
986 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
987 // Still no MANAGE_USERS.
988 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
989 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
990 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
991
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100992 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
993 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
994 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
995 dpm::getDeviceOwnerComponentOnAnyUser);
996 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
997 dpm::getDeviceOwnerUserId);
998 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
999 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001000
1001 // Restore.
1002 mContext.binder.callingUid = origCallingUser;
1003 mContext.callerPermissions.addAll(origPermissions);
1004 }
1005
1006
Makoto Onukib643fb02015-09-22 15:03:44 -07001007 /**
1008 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1009 */
1010 public void testSetDeviceOwner_noSuchPackage() {
1011 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001012 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001013 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1014 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1015
1016 // Call from a process on the system user.
1017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1018
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001019 assertExpectException(IllegalArgumentException.class,
1020 /* messageRegex= */ "Invalid component",
1021 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001022 }
1023
1024 public void testSetDeviceOwner_failures() throws Exception {
1025 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1026 }
1027
Makoto Onukia52562c2015-10-01 16:12:31 -07001028 public void testClearDeviceOwner() throws Exception {
1029 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001030 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001031 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1032 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1033
1034 // Set admin1 as a DA to the secondary user.
1035 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1036
1037 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1038
1039 // Set admin 1 as the DO to the system user.
1040
1041 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1042 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1043 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1044 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1045
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001046 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001047 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001048 eq(admin1.getPackageName()));
1049
Makoto Onukic8a5a552015-11-19 14:29:12 -08001050 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001051
Makoto Onuki90b89652016-01-28 14:44:18 -08001052 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001053 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001054 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001055
1056 assertTrue(dpm.isAdminActive(admin1));
1057 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1058
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001060 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001061
1062 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001063 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1064 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001065
1066 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001067 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001068 assertExpectException(IllegalStateException.class,
1069 /* messageRegex= */ "User must be running and unlocked",
1070 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001071
Pavel Grafov75c0a892017-05-18 17:28:27 +01001072 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1073 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001074 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1075
1076 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001077 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001078
Pavel Grafov75c0a892017-05-18 17:28:27 +01001079 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001080 eq(false),
1081 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1082
Pavel Grafov75c0a892017-05-18 17:28:27 +01001083 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001084 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001085 eq(null),
1086 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001087
Sudheer Shanka101c3532018-01-08 16:28:42 -08001088 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1089 null, UserHandle.USER_SYSTEM);
1090
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001091 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001092
1093 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1094 // and once for clearing it.
1095 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1096 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1097 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001098 // TODO Check other calls.
1099 }
1100
1101 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1102 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001103 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001104 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1105 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1106
1107 // Set admin1 as a DA to the secondary user.
1108 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1109
1110 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1111
1112 // Set admin 1 as the DO to the system user.
1113
1114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1115 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1116 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1117 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1118
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001119 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001120 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001121 eq(admin1.getPackageName()));
1122
Makoto Onukic8a5a552015-11-19 14:29:12 -08001123 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001124
1125 // Now call clear from the secondary user, which should throw.
1126 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1127
1128 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001129 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 eq(admin1.getPackageName()),
1131 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001132 assertExpectException(SecurityException.class,
1133 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1134 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001135
Makoto Onukic8a5a552015-11-19 14:29:12 -08001136 // DO shouldn't be removed.
1137 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001138 }
1139
Makoto Onukib643fb02015-09-22 15:03:44 -07001140 public void testSetProfileOwner() throws Exception {
1141 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001142
Makoto Onuki90b89652016-01-28 14:44:18 -08001143 // PO admin can't be deactivated.
1144 dpm.removeActiveAdmin(admin1);
1145 assertTrue(dpm.isAdminActive(admin1));
1146
Makoto Onuki803d6752015-10-30 12:58:39 -07001147 // Try setting DO on the same user, which should fail.
1148 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001149 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1150 runAsCaller(mServiceContext, dpms, dpm -> {
1151 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001152 assertExpectException(IllegalStateException.class,
1153 /* messageRegex= */ "already has a profile owner",
1154 () -> dpm.setDeviceOwner(admin2, "owner-name",
1155 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001157 }
1158
Makoto Onuki90b89652016-01-28 14:44:18 -08001159 public void testClearProfileOwner() throws Exception {
1160 setAsProfileOwner(admin1);
1161
1162 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1163
1164 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1165 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1166
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001167 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001168 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001169 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001170 assertExpectException(IllegalStateException.class,
1171 /* messageRegex= */ "User must be running and unlocked",
1172 () -> dpm.clearProfileOwner(admin1));
1173
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001174 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001175 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001176 dpm.clearProfileOwner(admin1);
1177
1178 // Check
1179 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001180 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001181 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1182 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001183 }
1184
Makoto Onukib643fb02015-09-22 15:03:44 -07001185 public void testSetProfileOwner_failures() throws Exception {
1186 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1187 }
1188
Makoto Onukia52562c2015-10-01 16:12:31 -07001189 public void testGetDeviceOwnerAdminLocked() throws Exception {
1190 checkDeviceOwnerWithMultipleDeviceAdmins();
1191 }
1192
1193 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1194 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1195 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1196 // make sure it gets the right component from the right user.
1197
1198 final int ANOTHER_USER_ID = 100;
1199 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1200
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001202
1203 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001204 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001205 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1206 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1207
1208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1209
Pavel Grafov75c0a892017-05-18 17:28:27 +01001210 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001211
Makoto Onukia52562c2015-10-01 16:12:31 -07001212 // Make sure the admin packge is installed to each user.
1213 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1214 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1215
1216 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1217 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1218
1219 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1220
1221
1222 // Set active admins to the users.
1223 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1224 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1225
1226 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1227 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1228
1229 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1230
1231 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001232 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001233 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1234
Makoto Onukic8a5a552015-11-19 14:29:12 -08001235 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001236
1237 // Then check getDeviceOwnerAdminLocked().
1238 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1239 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1240 }
1241
1242 /**
1243 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001244 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1245 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001246 *
1247 * We didn't use to persist the DO component class name, but now we do, and the above method
1248 * finds the right component from a package name upon migration.
1249 */
1250 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001251 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001252 checkDeviceOwnerWithMultipleDeviceAdmins();
1253
1254 // Overwrite the device owner setting and clears the clas name.
1255 dpms.mOwners.setDeviceOwner(
1256 new ComponentName(admin2.getPackageName(), ""),
1257 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1258 dpms.mOwners.writeDeviceOwner();
1259
1260 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001261 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001262
1263 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001264 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001266 initializeDpms();
1267
1268 // Now the DO component name is a full name.
1269 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1270 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001271 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001272 }
1273
Makoto Onukib643fb02015-09-22 15:03:44 -07001274 public void testSetGetApplicationRestriction() {
1275 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001276 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001277
1278 {
1279 Bundle rest = new Bundle();
1280 rest.putString("KEY_STRING", "Foo1");
1281 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1282 }
1283
1284 {
1285 Bundle rest = new Bundle();
1286 rest.putString("KEY_STRING", "Foo2");
1287 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1288 }
1289
1290 {
1291 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1292 assertNotNull(returned);
1293 assertEquals(returned.size(), 1);
1294 assertEquals(returned.get("KEY_STRING"), "Foo1");
1295 }
1296
1297 {
1298 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1299 assertNotNull(returned);
1300 assertEquals(returned.size(), 1);
1301 assertEquals(returned.get("KEY_STRING"), "Foo2");
1302 }
1303
1304 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1305 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1306 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001307
Edman Anjosf9946772016-11-28 16:35:15 +01001308 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001309 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1310 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001311 *
1312 * @param packageName the name of the package to be setup
1313 * @param appId the application ID to be given to the package
1314 * @return the UID of the package as known by the mock package manager
1315 */
1316 private int setupPackageInPackageManager(final String packageName, final int appId)
1317 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001318 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001319 ApplicationInfo.FLAG_HAS_CODE);
1320 }
1321
1322 /**
1323 * Setup a package in the package manager mock. Useful for faking installed applications.
1324 *
1325 * @param packageName the name of the package to be setup
1326 * @param userId the user id where the package will be "installed"
1327 * @param appId the application ID to be given to the package
1328 * @param flags flags to set in the ApplicationInfo for this package
1329 * @return the UID of the package as known by the mock package manager
1330 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001331 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1332 int flags) throws Exception {
1333 final int uid = UserHandle.getUid(userId, appId);
1334 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001335 final PackageInfo pi = new PackageInfo();
1336 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001337 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001338 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001339 eq(packageName),
1340 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001341 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001342 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001343 eq(packageName),
1344 anyInt(),
1345 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001346 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001347 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001348 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001349 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001350 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001351 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001352 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001353 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001354 return uid;
1355 }
1356
Robin Lee7f5c91c2017-02-08 21:27:02 +00001357 public void testCertificateDisclosure() throws Exception {
1358 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1359 final UserHandle user = UserHandle.of(userId);
1360
1361 mContext.applicationInfo = new ApplicationInfo();
1362 mContext.callerPermissions.add(permission.MANAGE_USERS);
1363 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001364 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001365 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1366
Robin Leeabaa0692017-02-20 20:54:22 +00001367 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1368 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001369
1370 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1371 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1372
1373 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001374 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001375 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001376 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001377 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001378 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001379 .cancelAsUser(anyString(), anyInt(), eq(user));
1380
1381 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001383 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001384 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1385 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001386 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001387 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001388 .notifyAsUser(anyString(), anyInt(), argThat(
1389 new BaseMatcher<Notification>() {
1390 @Override
1391 public boolean matches(Object item) {
1392 final Notification noti = (Notification) item;
1393 return TEST_STRING.equals(
1394 noti.extras.getString(Notification.EXTRA_TITLE));
1395 }
1396 @Override
1397 public void describeTo(Description description) {
1398 description.appendText(
1399 "Notification{title=\"" + TEST_STRING + "\"}");
1400 }
1401 }), eq(user));
1402 }
1403
Edman Anjosf9946772016-11-28 16:35:15 +01001404 /**
1405 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1406 * privileges can acually be exercised by a delegate are not covered here.
1407 */
1408 public void testDelegation() throws Exception {
1409 setAsProfileOwner(admin1);
1410
1411 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1412
1413 // Given two packages
1414 final String CERT_DELEGATE = "com.delegate.certs";
1415 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1416 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1417 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1418 20989);
1419
1420 // On delegation
1421 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1422 mContext.packageName = admin1.getPackageName();
1423 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1424 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1425
1426 // DPMS correctly stores and retrieves the delegates
1427 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1428 assertEquals(2, policy.mDelegationMap.size());
1429 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1430 DELEGATION_CERT_INSTALL);
1431 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1432 DELEGATION_CERT_INSTALL);
1433 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1434 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1435 DELEGATION_APP_RESTRICTIONS);
1436 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1437 DELEGATION_APP_RESTRICTIONS);
1438 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1439
1440 // On calling install certificate APIs from an unauthorized process
1441 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1442 mContext.packageName = RESTRICTIONS_DELEGATE;
1443
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001444 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1445 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001446
1447 // On calling install certificate APIs from an authorized process
1448 mContext.binder.callingUid = CERT_DELEGATE_UID;
1449 mContext.packageName = CERT_DELEGATE;
1450
1451 // DPMS executes without a SecurityException
1452 try {
1453 dpm.installCaCert(null, null);
1454 } catch (SecurityException unexpected) {
1455 fail("Threw SecurityException on authorized access");
1456 } catch (NullPointerException expected) {
1457 }
1458
1459 // On removing a delegate
1460 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1461 mContext.packageName = admin1.getPackageName();
1462 dpm.setCertInstallerPackage(admin1, null);
1463
1464 // DPMS does not allow access to ex-delegate
1465 mContext.binder.callingUid = CERT_DELEGATE_UID;
1466 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001467 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1468 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001469
1470 // But still allows access to other existing delegates
1471 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1472 mContext.packageName = RESTRICTIONS_DELEGATE;
1473 try {
1474 dpm.getApplicationRestrictions(null, "pkg");
1475 } catch (SecurityException expected) {
1476 fail("Threw SecurityException on authorized access");
1477 }
1478 }
1479
Esteban Talaverabf60f722015-12-10 16:26:44 +00001480 public void testApplicationRestrictionsManagingApp() throws Exception {
1481 setAsProfileOwner(admin1);
1482
Rubin Xued1928a2016-02-11 17:23:06 +00001483 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001484 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001485 final String nonDelegateExceptionMessageRegex =
1486 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001487 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001488 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1489 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001490
Esteban Talaverabf60f722015-12-10 16:26:44 +00001491 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1492 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001493 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1494 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001495 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001496 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001497 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001498 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1499 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001500
1501 // Check via the profile owner that no restrictions were set.
1502 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001503 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001504 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1505
Rubin Xued1928a2016-02-11 17:23:06 +00001506 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001507 assertExpectException(PackageManager.NameNotFoundException.class,
1508 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1509 () -> dpm.setApplicationRestrictionsManagingPackage(
1510 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001511
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 // Let appRestrictionsManagerPackage manage app restrictions
1513 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1514 assertEquals(appRestrictionsManagerPackage,
1515 dpm.getApplicationRestrictionsManagingPackage(admin1));
1516
1517 // Now that package should be able to set and retrieve app restrictions.
1518 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001519 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001520 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1521 dpm.setApplicationRestrictions(null, "pkg1", rest);
1522 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1523 assertEquals(1, returned.size(), 1);
1524 assertEquals("Foo1", returned.get("KEY_STRING"));
1525
1526 // The same app running on a separate user shouldn't be able to manage app restrictions.
1527 mContext.binder.callingUid = UserHandle.getUid(
1528 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1529 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001530 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1531 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532
1533 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1534 // too.
1535 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001536 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001537 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1538 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1539 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1540
1541 // Removing the ability for the package to manage app restrictions.
1542 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1543 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1544 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001545 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001546 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001547 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1548 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001549 }
1550
Makoto Onukia4f11972015-10-01 13:19:58 -07001551 public void testSetUserRestriction_asDo() throws Exception {
1552 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001553 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001554 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1555 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1556
1557 // First, set DO.
1558
1559 // Call from a process on the system user.
1560 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1561
1562 // Make sure admin1 is installed on system user.
1563 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001564
1565 // Call.
1566 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001567 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001568 UserHandle.USER_SYSTEM));
1569
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001570 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001571 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001572 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001573 DpmTestUtils.assertRestrictions(
1574 DpmTestUtils.newRestrictions(defaultRestrictions),
1575 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1576 );
1577 DpmTestUtils.assertRestrictions(
1578 DpmTestUtils.newRestrictions(defaultRestrictions),
1579 dpm.getUserRestrictions(admin1)
1580 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001581 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001582 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001583 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001584 eq(true) /* isDeviceOwner */,
1585 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001586 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001587 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001588
1589 for (String restriction : defaultRestrictions) {
1590 dpm.clearUserRestriction(admin1, restriction);
1591 }
1592
Esteban Talavera548a04b2016-12-20 15:22:30 +00001593 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001594 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595
1596 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001597 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001599 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1600 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602
Makoto Onukia4f11972015-10-01 13:19:58 -07001603 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001604 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001605 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001606 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1607 UserManager.DISALLOW_ADD_USER),
1608 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001609 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001610
Makoto Onuki068c54a2015-10-13 14:34:03 -07001611 DpmTestUtils.assertRestrictions(
1612 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001614 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1615 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001616 DpmTestUtils.assertRestrictions(
1617 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001618 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001619 dpm.getUserRestrictions(admin1)
1620 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001621
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 eq(UserHandle.USER_SYSTEM),
1625 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001627 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001628
Makoto Onuki068c54a2015-10-13 14:34:03 -07001629 DpmTestUtils.assertRestrictions(
1630 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1631 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1632 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001633 DpmTestUtils.assertRestrictions(
1634 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1635 dpm.getUserRestrictions(admin1)
1636 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001637
1638 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001639 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 eq(UserHandle.USER_SYSTEM),
1641 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001642 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001643 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001644
Esteban Talavera548a04b2016-12-20 15:22:30 +00001645 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001646
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1648 // DO sets them, the scope is global.
1649 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001650 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001652 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001655 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1656 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658
1659 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1660 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001661 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662
1663 // More tests.
1664 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001665 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001667 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1668 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001669 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670
1671 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 UserManager.DISALLOW_ADD_USER),
1676 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678
1679 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 eq(UserHandle.USER_SYSTEM),
1682 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 UserManager.DISALLOW_ADD_USER),
1685 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687
1688 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1689 // locally.
1690 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001691 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692
1693 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1694 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1695 dpm.setCameraDisabled(admin2, true);
1696
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001699 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 UserManager.DISALLOW_ADD_USER),
1702 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001704 // TODO Make sure restrictions are written to the file.
1705 }
1706
1707 public void testSetUserRestriction_asPo() {
1708 setAsProfileOwner(admin1);
1709
Makoto Onuki068c54a2015-10-13 14:34:03 -07001710 DpmTestUtils.assertRestrictions(
1711 DpmTestUtils.newRestrictions(),
1712 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1713 .ensureUserRestrictions()
1714 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001715
1716 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001717 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 eq(DpmMockContext.CALLER_USER_HANDLE),
1719 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001721 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722
Makoto Onukia4f11972015-10-01 13:19:58 -07001723 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 eq(DpmMockContext.CALLER_USER_HANDLE),
1726 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1727 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001729 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001730
Makoto Onuki068c54a2015-10-13 14:34:03 -07001731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(
1733 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1734 UserManager.DISALLOW_OUTGOING_CALLS
1735 ),
1736 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1737 .ensureUserRestrictions()
1738 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001739 DpmTestUtils.assertRestrictions(
1740 DpmTestUtils.newRestrictions(
1741 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1742 UserManager.DISALLOW_OUTGOING_CALLS
1743 ),
1744 dpm.getUserRestrictions(admin1)
1745 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001746
1747 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 eq(DpmMockContext.CALLER_USER_HANDLE),
1750 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001751 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001752 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001753
1754 DpmTestUtils.assertRestrictions(
1755 DpmTestUtils.newRestrictions(
1756 UserManager.DISALLOW_OUTGOING_CALLS
1757 ),
1758 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1759 .ensureUserRestrictions()
1760 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001761 DpmTestUtils.assertRestrictions(
1762 DpmTestUtils.newRestrictions(
1763 UserManager.DISALLOW_OUTGOING_CALLS
1764 ),
1765 dpm.getUserRestrictions(admin1)
1766 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001767
1768 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001770 eq(DpmMockContext.CALLER_USER_HANDLE),
1771 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001772 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001773 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001774
Makoto Onuki068c54a2015-10-13 14:34:03 -07001775 DpmTestUtils.assertRestrictions(
1776 DpmTestUtils.newRestrictions(),
1777 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1778 .ensureUserRestrictions()
1779 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001780 DpmTestUtils.assertRestrictions(
1781 DpmTestUtils.newRestrictions(),
1782 dpm.getUserRestrictions(admin1)
1783 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001784
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001785 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1786 // though when DO sets them they'll be applied globally.
1787 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001788 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001791 eq(DpmMockContext.CALLER_USER_HANDLE),
1792 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1793 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001794 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001795 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796
1797 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001798 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001800 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001801 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001802 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804
Makoto Onukia4f11972015-10-01 13:19:58 -07001805 // TODO Make sure restrictions are written to the file.
1806 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001807
Esteban Talavera548a04b2016-12-20 15:22:30 +00001808
1809 public void testDefaultEnabledUserRestrictions() throws Exception {
1810 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1811 mContext.callerPermissions.add(permission.MANAGE_USERS);
1812 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1813 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1814
1815 // First, set DO.
1816
1817 // Call from a process on the system user.
1818 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1819
1820 // Make sure admin1 is installed on system user.
1821 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1822
1823 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1824 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1825 UserHandle.USER_SYSTEM));
1826
1827 // Check that the user restrictions that are enabled by default are set. Then unset them.
1828 String[] defaultRestrictions = UserRestrictionsUtils
1829 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1830 assertTrue(defaultRestrictions.length > 0);
1831 DpmTestUtils.assertRestrictions(
1832 DpmTestUtils.newRestrictions(defaultRestrictions),
1833 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1834 );
1835 DpmTestUtils.assertRestrictions(
1836 DpmTestUtils.newRestrictions(defaultRestrictions),
1837 dpm.getUserRestrictions(admin1)
1838 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001839 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001840 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001841 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001842 eq(true) /* isDeviceOwner */,
1843 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001844 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001846
1847 for (String restriction : defaultRestrictions) {
1848 dpm.clearUserRestriction(admin1, restriction);
1849 }
1850
1851 assertNoDeviceOwnerRestrictions();
1852
1853 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001854 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001855 initializeDpms();
1856 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1857 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1858
1859 assertNoDeviceOwnerRestrictions();
1860
1861 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1862 // is set as it wasn't enabled during setDeviceOwner.
1863 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1864 assertFalse(UserRestrictionsUtils
1865 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1866 UserRestrictionsUtils
1867 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1868 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001869 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001870 initializeDpms();
1871 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1872 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1873
1874 DpmTestUtils.assertRestrictions(
1875 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1876 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1877 );
1878 DpmTestUtils.assertRestrictions(
1879 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1880 dpm.getUserRestrictions(admin1)
1881 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001884 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001885 eq(true) /* isDeviceOwner */,
1886 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001887 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001888 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001889
1890 // Remove the restriction.
1891 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1892
1893 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1894 initializeDpms();
1895 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1896 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1897 assertNoDeviceOwnerRestrictions();
1898 } finally {
1899 UserRestrictionsUtils
1900 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1901 }
1902 }
1903
1904 private void assertNoDeviceOwnerRestrictions() {
1905 DpmTestUtils.assertRestrictions(
1906 DpmTestUtils.newRestrictions(),
1907 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1908 );
1909 DpmTestUtils.assertRestrictions(
1910 DpmTestUtils.newRestrictions(),
1911 dpm.getUserRestrictions(admin1)
1912 );
1913 }
1914
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001915 public void testGetMacAddress() throws Exception {
1916 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1917 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1918 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1919
1920 // In this test, change the caller user to "system".
1921 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1922
1923 // Make sure admin1 is installed on system user.
1924 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1925
1926 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001927 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1928 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001929
1930 // DO needs to be an DA.
1931 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1932 assertTrue(dpm.isAdminActive(admin1));
1933
1934 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001935 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1936 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001937
1938 // Test 3. Caller has PO, but not DO.
1939 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001940 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1941 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001942
1943 // Remove PO.
1944 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001945 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001946 // Test 4, Caller is DO now.
1947 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1948
1949 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001950 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001951
1952 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001953 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001954 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001955
1956 // 4-3. With a real MAC address.
1957 final WifiInfo wi = new WifiInfo();
1958 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001959 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001960 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001961 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001962
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001963 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001964 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1966
1967 // In this test, change the caller user to "system".
1968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1969
1970 // Make sure admin1 is installed on system user.
1971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1972
1973 // Set admin1 as DA.
1974 dpm.setActiveAdmin(admin1, false);
1975 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001976 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1977 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001978
1979 // Set admin1 as PO.
1980 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001981 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1982 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001983
1984 // Remove PO and add DO.
1985 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001986 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001987 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1988
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001989 // admin1 is DO.
1990 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001991 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001992 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001993 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1994 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001995
1996 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001997 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001998 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001999 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2000 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002001
2002 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002003 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002004 dpm.reboot(admin1);
2005 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002006
2007 public void testSetGetSupportText() {
2008 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2009 dpm.setActiveAdmin(admin1, true);
2010 dpm.setActiveAdmin(admin2, true);
2011 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2012
2013 // Null default support messages.
2014 {
2015 assertNull(dpm.getLongSupportMessage(admin1));
2016 assertNull(dpm.getShortSupportMessage(admin1));
2017 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2018 assertNull(dpm.getShortSupportMessageForUser(admin1,
2019 DpmMockContext.CALLER_USER_HANDLE));
2020 assertNull(dpm.getLongSupportMessageForUser(admin1,
2021 DpmMockContext.CALLER_USER_HANDLE));
2022 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2023 }
2024
2025 // Only system can call the per user versions.
2026 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002027 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2028 () -> dpm.getShortSupportMessageForUser(admin1,
2029 DpmMockContext.CALLER_USER_HANDLE));
2030 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2031 () -> dpm.getLongSupportMessageForUser(admin1,
2032 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002033 }
2034
2035 // Can't set message for admin in another uid.
2036 {
2037 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002038 assertExpectException(SecurityException.class,
2039 /* messageRegex= */ "is not owned by uid",
2040 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002041 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2042 }
2043
2044 // Set/Get short returns what it sets and other admins text isn't changed.
2045 {
2046 final String supportText = "Some text to test with.";
2047 dpm.setShortSupportMessage(admin1, supportText);
2048 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2049 assertNull(dpm.getLongSupportMessage(admin1));
2050 assertNull(dpm.getShortSupportMessage(admin2));
2051
2052 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2053 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2054 DpmMockContext.CALLER_USER_HANDLE));
2055 assertNull(dpm.getShortSupportMessageForUser(admin2,
2056 DpmMockContext.CALLER_USER_HANDLE));
2057 assertNull(dpm.getLongSupportMessageForUser(admin1,
2058 DpmMockContext.CALLER_USER_HANDLE));
2059 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2060
2061 dpm.setShortSupportMessage(admin1, null);
2062 assertNull(dpm.getShortSupportMessage(admin1));
2063 }
2064
2065 // Set/Get long returns what it sets and other admins text isn't changed.
2066 {
2067 final String supportText = "Some text to test with.\nWith more text.";
2068 dpm.setLongSupportMessage(admin1, supportText);
2069 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2070 assertNull(dpm.getShortSupportMessage(admin1));
2071 assertNull(dpm.getLongSupportMessage(admin2));
2072
2073 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2074 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 assertNull(dpm.getLongSupportMessageForUser(admin2,
2077 DpmMockContext.CALLER_USER_HANDLE));
2078 assertNull(dpm.getShortSupportMessageForUser(admin1,
2079 DpmMockContext.CALLER_USER_HANDLE));
2080 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2081
2082 dpm.setLongSupportMessage(admin1, null);
2083 assertNull(dpm.getLongSupportMessage(admin1));
2084 }
2085 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002086
phweiss73145f42017-01-17 19:06:38 +01002087 public void testCreateAdminSupportIntent() throws Exception {
2088 // Setup device owner.
2089 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2090 setupDeviceOwner();
2091
2092 // Nonexisting permission returns null
2093 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2094 assertNull(intent);
2095
2096 // Existing permission that is not set returns null
2097 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2098 assertNull(intent);
2099
2100 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002101 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002102 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2103 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2104 .thenReturn(true);
2105 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2106 assertNull(intent);
2107
2108 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002109 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002110 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2111 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2112 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2113 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2114 assertNotNull(intent);
2115 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2116 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2117 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002118 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002119 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2120 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2121
2122 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2123 // user restrictions
2124
2125 // Camera is not disabled
2126 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2127 assertNull(intent);
2128
2129 // Camera is disabled
2130 dpm.setCameraDisabled(admin1, true);
2131 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2132 assertNotNull(intent);
2133 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2134 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2135
2136 // Screen capture is not disabled
2137 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2138 assertNull(intent);
2139
2140 // Screen capture is disabled
2141 dpm.setScreenCaptureDisabled(admin1, true);
2142 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2143 assertNotNull(intent);
2144 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2145 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2146
2147 // Same checks for different user
2148 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2149 // Camera should be disabled by device owner
2150 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2151 assertNotNull(intent);
2152 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2153 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2154 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2155 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2156 // ScreenCapture should not be disabled by device owner
2157 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2158 assertNull(intent);
2159 }
2160
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002161 /**
2162 * Test for:
2163 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002164 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002165 * {@link DevicePolicyManager#isAffiliatedUser}
2166 */
2167 public void testUserAffiliation() throws Exception {
2168 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2169 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2170 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2171
2172 // Check that the system user is unaffiliated.
2173 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2174 assertFalse(dpm.isAffiliatedUser());
2175
2176 // Set a device owner on the system user. Check that the system user becomes affiliated.
2177 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2178 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2179 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2180 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002181 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002182
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002183 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002184 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2185 setAsProfileOwner(admin2);
2186 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002187 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002188
2189 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2190 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002191 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002192 userAffiliationIds.add("red");
2193 userAffiliationIds.add("green");
2194 userAffiliationIds.add("blue");
2195 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002196 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002197 assertFalse(dpm.isAffiliatedUser());
2198
2199 // Have the device owner specify a set of affiliation ids that do not intersect with those
2200 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002201 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002202 deviceAffiliationIds.add("cyan");
2203 deviceAffiliationIds.add("yellow");
2204 deviceAffiliationIds.add("magenta");
2205 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2206 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002207 MoreAsserts.assertContentsInAnyOrder(
2208 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002209 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2210 assertFalse(dpm.isAffiliatedUser());
2211
2212 // Have the profile owner specify a set of affiliation ids that intersect with those
2213 // specified by the device owner. Check that the test user becomes affiliated.
2214 userAffiliationIds.add("yellow");
2215 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002216 MoreAsserts.assertContentsInAnyOrder(
2217 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002218 assertTrue(dpm.isAffiliatedUser());
2219
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002220 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002221 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002222 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002223 assertFalse(dpm.isAffiliatedUser());
2224
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002225 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2226 dpm.setAffiliationIds(admin2, userAffiliationIds);
2227 assertTrue(dpm.isAffiliatedUser());
2228 dpm.clearProfileOwner(admin2);
2229 assertFalse(dpm.isAffiliatedUser());
2230
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002231 // Check that the system user remains affiliated.
2232 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2233 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002234
2235 // Clear the device owner - the user becomes unaffiliated.
2236 clearDeviceOwner();
2237 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002238 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002239
2240 public void testGetUserProvisioningState_defaultResult() {
2241 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2242 }
2243
2244 public void testSetUserProvisioningState_permission() throws Exception {
2245 setupProfileOwner();
2246 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2247
2248 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2249 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2250 }
2251
2252 public void testSetUserProvisioningState_unprivileged() throws Exception {
2253 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002254 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2255 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2256 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002257 }
2258
2259 public void testSetUserProvisioningState_noManagement() {
2260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002261 assertExpectException(IllegalStateException.class,
2262 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2263 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2264 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002265 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2266 }
2267
2268 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2269 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2270 setupDeviceOwner();
2271 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2272
2273 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2274 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2275 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2276 }
2277
2278 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2279 throws Exception {
2280 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2281 setupDeviceOwner();
2282 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2283
2284 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2285 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2286 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2287 }
2288
2289 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2290 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2291 setupDeviceOwner();
2292 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2293
2294 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2295 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2296 }
2297
2298 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2299 throws Exception {
2300 setupProfileOwner();
2301 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2302
2303 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2304 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2305 DevicePolicyManager.STATE_USER_UNMANAGED);
2306 }
2307
2308 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2309 throws Exception {
2310 setupProfileOwner();
2311 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2312
2313 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2314 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2315 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2316 }
2317
2318 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2319 setupProfileOwner();
2320 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2321
2322 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2323 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2324 }
2325
2326 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2327 setupProfileOwner();
2328 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2329
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002330 assertExpectException(IllegalStateException.class,
2331 /* messageRegex= */ "Cannot move to user provisioning state",
2332 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2333 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2334 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002335 }
2336
2337 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2338 throws Exception {
2339 setupProfileOwner();
2340 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2341
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002342 assertExpectException(IllegalStateException.class,
2343 /* messageRegex= */ "Cannot move to user provisioning state",
2344 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2345 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2346 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002347 }
2348
2349 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2350 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2351 for (int state : states) {
2352 dpm.setUserProvisioningState(state, userId);
2353 assertEquals(state, dpm.getUserProvisioningState());
2354 }
2355 }
2356
2357 private void setupProfileOwner() throws Exception {
2358 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2359
2360 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2361 dpm.setActiveAdmin(admin1, false);
2362 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2363
2364 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2365 }
2366
2367 private void setupDeviceOwner() throws Exception {
2368 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2369
2370 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2371 dpm.setActiveAdmin(admin1, false);
2372 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2373
2374 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2375 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002376
2377 public void testSetMaximumTimeToLock() {
2378 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2379
2380 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2381 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2382
Pavel Grafov75c0a892017-05-18 17:28:27 +01002383 reset(getServices().powerManagerInternal);
2384 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002385
2386 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002387 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2388 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002389 reset(getServices().powerManagerInternal);
2390 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002391
2392 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002393 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2394 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002395 reset(getServices().powerManagerInternal);
2396 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002397
2398 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002399 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2400 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002401 reset(getServices().powerManagerInternal);
2402 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002403
2404 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002405 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2406 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002407 reset(getServices().powerManagerInternal);
2408 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002409
2410 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002411 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2412 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002413 reset(getServices().powerManagerInternal);
2414 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002415
2416 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002417 reset(getServices().powerManagerInternal);
2418 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002419
Pavel Grafov28939982017-10-03 15:11:52 +01002420 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2421 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2422 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002423 reset(getServices().powerManagerInternal);
2424 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002425
2426 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002427 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2428 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002429 reset(getServices().powerManagerInternal);
2430 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002431
Pavel Grafov28939982017-10-03 15:11:52 +01002432 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002433 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002434 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2435 verifyStayOnWhilePluggedCleared(false);
2436 }
2437
2438 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2439 // uses separate challenge.
2440 public void testSetMaximumTimeToLockProfile() throws Exception {
2441 final int PROFILE_USER = 15;
2442 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2443 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2444 mContext.binder.callingUid = PROFILE_ADMIN;
2445 final DevicePolicyManagerInternal dpmi =
2446 LocalServices.getService(DevicePolicyManagerInternal.class);
2447
2448 dpm.setMaximumTimeToLock(admin1, 0);
2449
2450 reset(getServices().powerManagerInternal);
2451 reset(getServices().settings);
2452
2453 // First add timeout for the profile.
2454 dpm.setMaximumTimeToLock(admin1, 10);
2455 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2456
2457 reset(getServices().powerManagerInternal);
2458 reset(getServices().settings);
2459
2460 // Add separate challenge
2461 when(getServices().lockPatternUtils
2462 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2463 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2464
2465 verifyScreenTimeoutCall(10L, PROFILE_USER);
2466 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2467
2468 reset(getServices().powerManagerInternal);
2469 reset(getServices().settings);
2470
2471 // Remove the timeout.
2472 dpm.setMaximumTimeToLock(admin1, 0);
2473 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2474 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2475
2476 reset(getServices().powerManagerInternal);
2477 reset(getServices().settings);
2478
2479 // Add it back.
2480 dpm.setMaximumTimeToLock(admin1, 10);
2481 verifyScreenTimeoutCall(10L, PROFILE_USER);
2482 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2483
2484 reset(getServices().powerManagerInternal);
2485 reset(getServices().settings);
2486
2487 // Remove separate challenge.
2488 reset(getServices().lockPatternUtils);
2489 when(getServices().lockPatternUtils
2490 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2491 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2492
2493 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2494 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2495
2496 reset(getServices().powerManagerInternal);
2497 reset(getServices().settings);
2498
2499 // Remove the timeout.
2500 dpm.setMaximumTimeToLock(admin1, 0);
2501 verifyScreenTimeoutCall(null, PROFILE_USER);
2502 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002503 }
2504
Michal Karpinski943aabd2016-10-06 11:09:25 +01002505 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2506 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2507 setupDeviceOwner();
2508 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2509
Michal Karpinskid084ca52017-01-18 15:54:18 +00002510 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2511 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2512 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2513 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2514 - ONE_MINUTE;
2515
2516 // verify that the minimum timeout cannot be modified on user builds (system property is
2517 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002518 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002519
2520 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2521 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2522 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2523
Pavel Grafov75c0a892017-05-18 17:28:27 +01002524 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002525
2526 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002527 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002528
Michal Karpinskid084ca52017-01-18 15:54:18 +00002529 // reset to default (0 means the admin is not participating, so default should be returned)
2530 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002531
2532 // aggregation should be the default if unset by any admin
2533 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2534 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2535
2536 // admin not participating by default
2537 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2538
2539 //clamping from the top
2540 dpm.setRequiredStrongAuthTimeout(admin1,
2541 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2542 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2543 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2544 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2545 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2546
Michal Karpinskid084ca52017-01-18 15:54:18 +00002547 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002548 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2549 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2550 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2551 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2552
2553 // clamping from the bottom
2554 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2555 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2556 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2557
Michal Karpinskid084ca52017-01-18 15:54:18 +00002558 // values within range
2559 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2560 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2561 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2562
2563 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2564 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2565 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002566
2567 // reset to default
2568 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2569 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2570 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2571 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2572
2573 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002574 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2575 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002576 }
2577
Pavel Grafov28939982017-10-03 15:11:52 +01002578 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002579 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002580 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002581 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002582 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002583 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002584 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002585 }
Pavel Grafov28939982017-10-03 15:11:52 +01002586 }
2587
2588 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002589 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2590 // UnfinishedVerificationException.
2591 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002592
Esteban Talavera01576862016-12-15 11:16:44 +00002593 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002594 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002595 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002596 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002597 .thenReturn(false);
2598 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002599 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2600 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002601 .thenReturn(true);
2602 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2603
2604 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002605 }
Victor Chang3e794af2016-03-04 13:48:17 +00002606
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002607 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2608 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002609 mContext.packageName = admin1.getPackageName();
2610 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002611 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2612 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2613 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2614 false);
2615 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2616 }
2617
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002618 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2619 setup_DeviceAdminFeatureOff();
2620 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2621 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2622 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2623 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2624 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2625 assertCheckProvisioningPreCondition(
2626 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2627 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2628 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2629 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2630 }
2631
Esteban Talavera01576862016-12-15 11:16:44 +00002632 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002633 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002634 .thenReturn(false);
2635 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002636 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2637 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002638 .thenReturn(true);
2639 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2640
2641 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002642 }
Victor Chang3e794af2016-03-04 13:48:17 +00002643
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002644 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2645 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002646 mContext.packageName = admin1.getPackageName();
2647 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002648 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2649 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2651 false);
2652 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2653
2654 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002655 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002656 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2657 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2658 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2659 true);
2660 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2661 }
2662
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002663 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2664 setup_ManagedProfileFeatureOff();
2665 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2666 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2667 DevicePolicyManager.CODE_OK);
2668 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2669 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2670 assertCheckProvisioningPreCondition(
2671 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2672 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2673 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2674 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2675
2676 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002677 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002678 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2679 DevicePolicyManager.CODE_OK);
2680 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2681 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2682 assertCheckProvisioningPreCondition(
2683 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2684 DevicePolicyManager.CODE_OK);
2685 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2686 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2687 }
2688
Esteban Talavera01576862016-12-15 11:16:44 +00002689 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002690 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002691 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002692 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2693 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002694 .thenReturn(true);
2695 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2696
2697 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002698 }
Victor Chang3e794af2016-03-04 13:48:17 +00002699
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002700 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2701 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002702 mContext.packageName = admin1.getPackageName();
2703 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002704 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2705 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2707 false /* because of non-split user */);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2709 false /* because of non-split user */);
2710 }
2711
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002712 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002713 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002714 setup_nonSplitUser_firstBoot_primaryUser();
2715 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2717 DevicePolicyManager.CODE_OK);
2718 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2719 DevicePolicyManager.CODE_OK);
2720 assertCheckProvisioningPreCondition(
2721 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2722 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2723 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2724 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2725 }
2726
Esteban Talavera01576862016-12-15 11:16:44 +00002727 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002729 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002730 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2731 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002732 .thenReturn(true);
2733 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2734
2735 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 }
Victor Chang3e794af2016-03-04 13:48:17 +00002737
Nicolas Prevot45d29072017-01-18 16:11:19 +00002738 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2739 setDeviceOwner();
2740 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2741 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2742 }
2743
2744 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2745 setup_nonSplitUser_withDo_primaryUser();
2746 final int MANAGED_PROFILE_USER_ID = 18;
2747 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2748 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002749 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002750 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002751 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002752 true)).thenReturn(true);
2753 }
2754
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002755 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2756 throws Exception {
2757 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002758 mContext.packageName = admin1.getPackageName();
2759 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002760 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2761 false/* because of completed device setup */);
2762 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2763 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2764 false/* because of non-split user */);
2765 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2766 false/* because of non-split user */);
2767 }
2768
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002769 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2770 throws Exception {
2771 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2772 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2773 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2774 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2775 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2776 DevicePolicyManager.CODE_OK);
2777 assertCheckProvisioningPreCondition(
2778 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2779 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2780 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2781 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2782 }
2783
Nicolas Prevot45d29072017-01-18 16:11:19 +00002784 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2785 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002786 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002787 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2788
2789 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2790 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002792
2793 // COMP mode is allowed.
2794 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2795 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002796 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002797
Nicolas Prevot45d29072017-01-18 16:11:19 +00002798 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002799 assertCheckProvisioningPreCondition(
2800 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002801 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002802 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002803 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2804 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2805 }
Esteban Talavera01576862016-12-15 11:16:44 +00002806
Nicolas Prevot45d29072017-01-18 16:11:19 +00002807 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2808 setup_nonSplitUser_withDo_primaryUser();
2809 mContext.packageName = admin1.getPackageName();
2810 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2811 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2812 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002813 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002814 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2815 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2816 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002817 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002818 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2819 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2820 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2821 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2822 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002823 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002824 assertCheckProvisioningPreCondition(
2825 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002826 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002827 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002828 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2829 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2830 }
Esteban Talavera01576862016-12-15 11:16:44 +00002831
Nicolas Prevot45d29072017-01-18 16:11:19 +00002832 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2833 throws Exception {
2834 setup_nonSplitUser_withDo_primaryUser();
2835 mContext.packageName = admin1.getPackageName();
2836 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002837 // The DO should not be allowed to initiate provisioning if the restriction is set by
2838 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002839 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002840 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2841 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2842 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002843 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002844 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2845 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2846 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2847 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2848 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002849 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2850
2851 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002852 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002853 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002854 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002855 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2856 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2857 }
2858
2859 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2860 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2861 mContext.packageName = admin1.getPackageName();
2862 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2863
2864 // We can delete the managed profile to create a new one, so provisioning is allowed.
2865 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2866 DevicePolicyManager.CODE_OK);
2867 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2868 assertCheckProvisioningPreCondition(
2869 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2870 DpmMockContext.ANOTHER_PACKAGE_NAME,
2871 DevicePolicyManager.CODE_OK);
2872 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2873 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2874 }
2875
2876 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2877 throws Exception {
2878 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2879 mContext.packageName = admin1.getPackageName();
2880 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002881 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002882 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2883 eq(UserHandle.SYSTEM)))
2884 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002885 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002886 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2887 eq(UserHandle.SYSTEM)))
2888 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002889
2890 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002891 assertCheckProvisioningPreCondition(
2892 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2893 DpmMockContext.ANOTHER_PACKAGE_NAME,
2894 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2896 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002897
2898 // But the device owner can still do it because it has set the restriction itself.
2899 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2900 DevicePolicyManager.CODE_OK);
2901 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002902 }
2903
2904 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002905 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002906 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002907 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2908 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002909 .thenReturn(false);
2910 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2911
2912 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002913 }
Victor Chang3e794af2016-03-04 13:48:17 +00002914
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002915 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2916 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002917 mContext.packageName = admin1.getPackageName();
2918 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2921 false /* because canAddMoreManagedProfiles returns false */);
2922 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2923 true);
2924 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2925 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002926 }
2927
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2929 throws Exception {
2930 setup_splitUser_firstBoot_systemUser();
2931 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2932 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2933 DevicePolicyManager.CODE_OK);
2934 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002935 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002936 assertCheckProvisioningPreCondition(
2937 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2938 DevicePolicyManager.CODE_OK);
2939 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2940 DevicePolicyManager.CODE_SYSTEM_USER);
2941 }
2942
Esteban Talavera01576862016-12-15 11:16:44 +00002943 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002944 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002945 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002946 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2947 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002948 .thenReturn(false);
2949 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2950
2951 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002952 }
Victor Chang3e794af2016-03-04 13:48:17 +00002953
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002954 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2955 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002956 mContext.packageName = admin1.getPackageName();
2957 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2959 true/* it's undefined behavior. Can be changed into false in the future */);
2960 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2961 false /* because canAddMoreManagedProfiles returns false */);
2962 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2963 true/* it's undefined behavior. Can be changed into false in the future */);
2964 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2965 false/* because calling uid is system user */);
2966 }
2967
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002968 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2969 throws Exception {
2970 setup_splitUser_afterDeviceSetup_systemUser();
2971 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2972 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2973 DevicePolicyManager.CODE_OK);
2974 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002975 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002976 assertCheckProvisioningPreCondition(
2977 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2978 DevicePolicyManager.CODE_OK);
2979 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2980 DevicePolicyManager.CODE_SYSTEM_USER);
2981 }
2982
Esteban Talavera01576862016-12-15 11:16:44 +00002983 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002984 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002985 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002986 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2987 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +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 }
Victor Chang3e794af2016-03-04 13:48:17 +00002993
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002994 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2995 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002996 mContext.packageName = admin1.getPackageName();
2997 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2999 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3001 true);
3002 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003003 }
3004
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003005 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003006 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003007 setup_splitUser_firstBoot_primaryUser();
3008 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3009 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3010 DevicePolicyManager.CODE_OK);
3011 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3012 DevicePolicyManager.CODE_OK);
3013 assertCheckProvisioningPreCondition(
3014 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3015 DevicePolicyManager.CODE_OK);
3016 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3017 DevicePolicyManager.CODE_OK);
3018 }
3019
Esteban Talavera01576862016-12-15 11:16:44 +00003020 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003021 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003022 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003023 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3024 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003025 true)).thenReturn(true);
3026 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3027
3028 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003029 }
Victor Chang3e794af2016-03-04 13:48:17 +00003030
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003031 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3032 throws Exception {
3033 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003034 mContext.packageName = admin1.getPackageName();
3035 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003036 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3037 true/* it's undefined behavior. Can be changed into false in the future */);
3038 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3039 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3040 true/* it's undefined behavior. Can be changed into false in the future */);
3041 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3042 false/* because user setup completed */);
3043 }
3044
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003045 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003046 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003047 setup_splitUser_afterDeviceSetup_primaryUser();
3048 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3049 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3050 DevicePolicyManager.CODE_OK);
3051 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3052 DevicePolicyManager.CODE_OK);
3053 assertCheckProvisioningPreCondition(
3054 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3055 DevicePolicyManager.CODE_OK);
3056 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3057 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3058 }
3059
Esteban Talavera01576862016-12-15 11:16:44 +00003060 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003061 setDeviceOwner();
3062
Pavel Grafov75c0a892017-05-18 17:28:27 +01003063 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003064 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003065 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3066 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003067 .thenReturn(false);
3068 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3069
3070 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003071 }
Victor Chang3e794af2016-03-04 13:48:17 +00003072
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003073 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3074 throws Exception {
3075 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003076 mContext.packageName = admin1.getPackageName();
3077 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3079 false /* can't provision managed profile on system user */);
3080 }
3081
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003082 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003083 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3085 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3086 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3087 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3088 }
3089
3090 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003091 setDeviceOwner();
3092
Pavel Grafov75c0a892017-05-18 17:28:27 +01003093 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003094 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003095 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3096 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003097 true)).thenReturn(true);
3098 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3099
3100 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 }
Victor Chang3e794af2016-03-04 13:48:17 +00003102
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003103 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3104 throws Exception {
3105 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003106 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3107 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003108 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3109 }
3110
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003111 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003112 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003113 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3114 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003115
3116 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003117 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3118 DevicePolicyManager.CODE_OK);
3119 }
3120
3121 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003122 setDeviceOwner();
3123
Pavel Grafov75c0a892017-05-18 17:28:27 +01003124 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003125 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003126 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3127 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003128 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3129 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003130 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003131 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003132 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003133 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003134 true)).thenReturn(true);
3135 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3136
3137 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003138 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003139
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003140 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3141 throws Exception {
3142 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003143 mContext.packageName = admin1.getPackageName();
3144 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003145 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3146 }
3147
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003148 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3149 throws Exception {
3150 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3151 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3152 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3153 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3154 }
3155
3156 public void testCheckProvisioningPreCondition_permission() {
3157 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003158 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3159 () -> dpm.checkProvisioningPreCondition(
3160 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 }
3162
Victor Chang3577ed22016-08-25 18:49:26 +01003163 public void testForceUpdateUserSetupComplete_permission() {
3164 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003165 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3166 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003167 }
3168
3169 public void testForceUpdateUserSetupComplete_systemUser() {
3170 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3171 // GIVEN calling from user 20
3172 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003173 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3174 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003175 }
3176
3177 public void testForceUpdateUserSetupComplete_userbuild() {
3178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3179 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3180
3181 final int userId = UserHandle.USER_SYSTEM;
3182 // GIVEN userComplete is false in SettingsProvider
3183 setUserSetupCompleteForUser(false, userId);
3184
3185 // GIVEN userComplete is true in DPM
3186 DevicePolicyManagerService.DevicePolicyData userData =
3187 new DevicePolicyManagerService.DevicePolicyData(userId);
3188 userData.mUserSetupComplete = true;
3189 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3190
3191 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003192 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003193
3194 assertTrue(dpms.hasUserSetupCompleted());
3195
3196 dpm.forceUpdateUserSetupComplete();
3197
3198 // THEN the state in dpms is not changed
3199 assertTrue(dpms.hasUserSetupCompleted());
3200 }
3201
3202 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3203 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3205
3206 final int userId = UserHandle.USER_SYSTEM;
3207 // GIVEN userComplete is false in SettingsProvider
3208 setUserSetupCompleteForUser(false, userId);
3209
3210 // GIVEN userComplete is true in DPM
3211 DevicePolicyManagerService.DevicePolicyData userData =
3212 new DevicePolicyManagerService.DevicePolicyData(userId);
3213 userData.mUserSetupComplete = true;
3214 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3215
3216 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003217 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003218
3219 assertTrue(dpms.hasUserSetupCompleted());
3220
3221 dpm.forceUpdateUserSetupComplete();
3222
3223 // THEN the state in dpms is not changed
3224 assertFalse(dpms.hasUserSetupCompleted());
3225 }
3226
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003227 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003228 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003229 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003230
3231 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3232 runAsCaller(mAdmin1Context, dpms, dpm -> {
3233 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3234 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003235 }
3236
3237 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3238 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3239 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003240
3241 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3242 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003243 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003244 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3245 .thenReturn(true);
3246
3247 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003248 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003249
3250 // Enabling logging should not change the timestamp.
3251 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003252 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003253 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003254 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003255 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003256 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003257
3258 // Retrieving the logs should update the timestamp.
3259 final long beforeRetrieval = System.currentTimeMillis();
3260 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003261 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003262 final long afterRetrieval = System.currentTimeMillis();
3263 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3264 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3265
3266 // Retrieving the pre-boot logs should update the timestamp.
3267 Thread.sleep(2);
3268 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003269 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003270 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3271
3272 // Checking the timestamp again should not change it.
3273 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003274 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003275
3276 // Retrieving the logs again should update the timestamp.
3277 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003278 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003279 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3280
3281 // Disabling logging should not change the timestamp.
3282 Thread.sleep(2);
3283 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003284 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003285
3286 // Restarting the DPMS should not lose the timestamp.
3287 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003288 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003289
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003290 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3291 mContext.binder.callingUid = 1234567;
3292 mContext.callerPermissions.add(permission.MANAGE_USERS);
3293 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3294 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3295
3296 // System can retrieve the timestamp.
3297 mContext.binder.clearCallingIdentity();
3298 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3299
3300 // Removing the device owner should clear the timestamp.
3301 clearDeviceOwner();
3302 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003303 }
3304
yuemingw0de748d2017-11-15 19:22:27 +00003305 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3307 setupDeviceOwner();
3308 assertExpectException(SecurityException.class, null, () ->
3309 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3310 }
3311
3312 public void testSetSystemSettingFailWithPO() throws Exception {
3313 setupProfileOwner();
3314 assertExpectException(SecurityException.class, null, () ->
3315 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3316 }
3317
3318 public void testSetSystemSetting() throws Exception {
3319 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3320 setupDeviceOwner();
3321 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3322 verify(getServices().settings).settingsSystemPutString(
3323 Settings.System.SCREEN_BRIGHTNESS, "0");
3324 }
3325
yuemingwe43cdf72017-10-12 16:52:11 +01003326 public void testSetTime() throws Exception {
3327 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3328 setupDeviceOwner();
3329 dpm.setTime(admin1, 0);
3330 verify(getServices().alarmManager).setTime(0);
3331 }
3332
3333 public void testSetTimeFailWithPO() throws Exception {
3334 setupProfileOwner();
3335 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3336 }
3337
3338 public void testSetTimeWithAutoTimeOn() throws Exception {
3339 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3340 setupDeviceOwner();
3341 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3342 .thenReturn(1);
3343 assertFalse(dpm.setTime(admin1, 0));
3344 }
3345
3346 public void testSetTimeZone() throws Exception {
3347 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3348 setupDeviceOwner();
3349 dpm.setTimeZone(admin1, "Asia/Shanghai");
3350 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3351 }
3352
3353 public void testSetTimeZoneFailWithPO() throws Exception {
3354 setupProfileOwner();
3355 assertExpectException(SecurityException.class, null,
3356 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3357 }
3358
3359 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3360 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3361 setupDeviceOwner();
3362 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3363 .thenReturn(1);
3364 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3365 }
3366
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003367 public void testGetLastBugReportRequestTime() throws Exception {
3368 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3369 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003370
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003371 mContext.packageName = admin1.getPackageName();
3372 mContext.applicationInfo = new ApplicationInfo();
3373 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3374 .thenReturn(Color.WHITE);
3375 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3376 anyObject())).thenReturn(Color.WHITE);
3377
Esteban Talaverad36dd152016-12-15 08:51:45 +00003378 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3379 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003380 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003381
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003382 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003383 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003384
3385 // Requesting a bug report should update the timestamp.
3386 final long beforeRequest = System.currentTimeMillis();
3387 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003388 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003389 final long afterRequest = System.currentTimeMillis();
3390 assertTrue(bugReportRequestTime >= beforeRequest);
3391 assertTrue(bugReportRequestTime <= afterRequest);
3392
3393 // Checking the timestamp again should not change it.
3394 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003395 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003396
3397 // Restarting the DPMS should not lose the timestamp.
3398 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003399 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003400
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003401 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3402 mContext.binder.callingUid = 1234567;
3403 mContext.callerPermissions.add(permission.MANAGE_USERS);
3404 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3405 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3406
3407 // System can retrieve the timestamp.
3408 mContext.binder.clearCallingIdentity();
3409 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3410
3411 // Removing the device owner should clear the timestamp.
3412 clearDeviceOwner();
3413 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003414 }
3415
3416 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3417 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3418 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003419 mContext.packageName = admin1.getPackageName();
3420 mContext.applicationInfo = new ApplicationInfo();
3421 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3422 .thenReturn(Color.WHITE);
3423 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3424 anyObject())).thenReturn(Color.WHITE);
3425
3426 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3427 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003428 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003429 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003430 .thenReturn(true);
3431
3432 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003433 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003434
3435 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3436 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003437 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003438
3439 // Enabling logging should not change the timestamp.
3440 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003441 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003442
3443 // Retrieving the logs should update the timestamp.
3444 final long beforeRetrieval = System.currentTimeMillis();
3445 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003446 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003447 final long afterRetrieval = System.currentTimeMillis();
3448 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3449 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3450
3451 // Checking the timestamp again should not change it.
3452 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003453 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003454
3455 // Retrieving the logs again should update the timestamp.
3456 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003457 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003458 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3459
3460 // Disabling logging should not change the timestamp.
3461 Thread.sleep(2);
3462 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003463 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003464
3465 // Restarting the DPMS should not lose the timestamp.
3466 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003467 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3468
3469 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3470 mContext.binder.callingUid = 1234567;
3471 mContext.callerPermissions.add(permission.MANAGE_USERS);
3472 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3473 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3474
3475 // System can retrieve the timestamp.
3476 mContext.binder.clearCallingIdentity();
3477 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3478
3479 // Removing the device owner should clear the timestamp.
3480 clearDeviceOwner();
3481 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003482 }
3483
Tony Mak2f26b792016-11-28 17:54:51 +00003484 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3485 // Setup device owner.
3486 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3487 setupDeviceOwner();
3488
3489 // Only device owner is setup, the result list should be empty.
3490 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3491 MoreAsserts.assertEmpty(targetUsers);
3492
3493 // Setup a managed profile managed by the same admin.
3494 final int MANAGED_PROFILE_USER_ID = 15;
3495 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3496 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3497
3498 // Add a secondary user, it should never talk with.
3499 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003500 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003501
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003502 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3503 // other.
3504 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3505 MoreAsserts.assertEmpty(targetUsers);
3506
3507 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3508 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3509 MoreAsserts.assertEmpty(targetUsers);
3510
3511 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003512 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003513 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3514 dpm.setAffiliationIds(admin1, userAffiliationIds);
3515
3516 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3517 dpm.setAffiliationIds(admin1, userAffiliationIds);
3518
Tony Mak2f26b792016-11-28 17:54:51 +00003519 // Calling from device owner admin, the result list should just contain the managed
3520 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003521 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003522 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3523 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3524
3525 // Calling from managed profile admin, the result list should just contain the system
3526 // user id.
3527 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3528 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3529 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003530
3531 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003532 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003533
3534 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3535 // to each other.
3536 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3537 MoreAsserts.assertEmpty(targetUsers);
3538
3539 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3540 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3541 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003542 }
3543
3544 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3545 // Setup a device owner.
3546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3547 setupDeviceOwner();
3548
3549 // Set up a managed profile managed by different package.
3550 final int MANAGED_PROFILE_USER_ID = 15;
3551 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3552 final ComponentName adminDifferentPackage =
3553 new ComponentName("another.package", "whatever.class");
3554 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3555
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003556 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003557 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003558 dpm.setAffiliationIds(admin1, userAffiliationIds);
3559
3560 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3561 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3562
Tony Mak2f26b792016-11-28 17:54:51 +00003563 // Calling from device owner admin, we should get zero bind device admin target users as
3564 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003565 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003566 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3567 MoreAsserts.assertEmpty(targetUsers);
3568
3569 // Calling from managed profile admin, we should still get zero target users for the same
3570 // reason.
3571 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3572 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3573 MoreAsserts.assertEmpty(targetUsers);
3574 }
3575
Charles Hee078db72017-10-19 18:03:20 +01003576 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003577 // Setup a device owner.
3578 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3579 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003580 // Lock task policy is updated when loading user data.
3581 verify(getServices().iactivityManager).updateLockTaskPackages(
3582 UserHandle.USER_SYSTEM, new String[0]);
3583 verify(getServices().iactivityManager).updateLockTaskFeatures(
3584 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003585
3586 // Set up a managed profile managed by different package (package name shouldn't matter)
3587 final int MANAGED_PROFILE_USER_ID = 15;
3588 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3589 final ComponentName adminDifferentPackage =
3590 new ComponentName("another.package", "whatever.class");
3591 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003592 verify(getServices().iactivityManager).updateLockTaskPackages(
3593 MANAGED_PROFILE_USER_ID, new String[0]);
3594 verify(getServices().iactivityManager).updateLockTaskFeatures(
3595 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003596
3597 // The DO can still set lock task packages
3598 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3599 final String[] doPackages = {"doPackage1", "doPackage2"};
3600 dpm.setLockTaskPackages(admin1, doPackages);
3601 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3602 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3603 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003604 verify(getServices().iactivityManager).updateLockTaskPackages(
3605 UserHandle.USER_SYSTEM, doPackages);
3606 // And the DO can still set lock task features
3607 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3608 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3609 dpm.setLockTaskFeatures(admin1, doFlags);
3610 verify(getServices().iactivityManager).updateLockTaskFeatures(
3611 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003612
3613 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3614 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3615 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003616 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3617 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3618 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3619 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003620 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003621 // And it shouldn't be able to setLockTaskFeatures.
3622 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3623 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3624 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3625 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003626
3627 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003628 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003629 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3630 dpm.setAffiliationIds(admin1, userAffiliationIds);
3631
3632 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3633 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3634
3635 // Now the managed profile can set lock task packages.
3636 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3637 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3638 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3639 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003640 verify(getServices().iactivityManager).updateLockTaskPackages(
3641 MANAGED_PROFILE_USER_ID, poPackages);
3642 // And it can set lock task features.
3643 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3644 verify(getServices().iactivityManager).updateLockTaskFeatures(
3645 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003646
3647 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003648 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003649 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3650 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003651 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3652 MANAGED_PROFILE_USER_ID, new String[0]);
3653 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3654 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003655
3656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3657 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3658 }
3659
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003660 public void testIsDeviceManaged() throws Exception {
3661 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3662 setupDeviceOwner();
3663
3664 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3665 // find out that the device has a device owner.
3666 assertTrue(dpm.isDeviceManaged());
3667 mContext.binder.callingUid = 1234567;
3668 mContext.callerPermissions.add(permission.MANAGE_USERS);
3669 assertTrue(dpm.isDeviceManaged());
3670 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3671 mContext.binder.clearCallingIdentity();
3672 assertTrue(dpm.isDeviceManaged());
3673
3674 clearDeviceOwner();
3675
3676 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3677 // not have a device owner.
3678 mContext.binder.callingUid = 1234567;
3679 mContext.callerPermissions.add(permission.MANAGE_USERS);
3680 assertFalse(dpm.isDeviceManaged());
3681 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3682 mContext.binder.clearCallingIdentity();
3683 assertFalse(dpm.isDeviceManaged());
3684 }
3685
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003686 public void testDeviceOwnerOrganizationName() throws Exception {
3687 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3688 setupDeviceOwner();
3689
3690 dpm.setOrganizationName(admin1, "organization");
3691
3692 // Device owner can retrieve organization managing the device.
3693 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3694
3695 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3696 mContext.binder.callingUid = 1234567;
3697 mContext.callerPermissions.add(permission.MANAGE_USERS);
3698 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3699 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3700
3701 // System can retrieve organization managing the device.
3702 mContext.binder.clearCallingIdentity();
3703 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3704
3705 // Removing the device owner clears the organization managing the device.
3706 clearDeviceOwner();
3707 assertNull(dpm.getDeviceOwnerOrganizationName());
3708 }
3709
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003710 public void testWipeDataManagedProfile() throws Exception {
3711 final int MANAGED_PROFILE_USER_ID = 15;
3712 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3713 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3714 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3715
3716 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003717 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003718 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003719 // Get mock reason string since we throw an IAE with empty string input.
3720 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3721 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003722
3723 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003724 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003725 MANAGED_PROFILE_USER_ID);
3726 }
3727
3728 public void testWipeDataManagedProfileDisallowed() throws Exception {
3729 final int MANAGED_PROFILE_USER_ID = 15;
3730 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3731 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3732
3733 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003734 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003735 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3736
Pavel Grafov75c0a892017-05-18 17:28:27 +01003737 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003738 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3739 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3740 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003741 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3742 thenReturn("Just a test string.");
3743
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003744 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003745 // The PO is not allowed to remove the profile if the user restriction was set on the
3746 // profile by the system
3747 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3748 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003749 }
3750
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003751 public void testWipeDataDeviceOwner() throws Exception {
3752 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003753 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003754 UserManager.DISALLOW_FACTORY_RESET,
3755 UserHandle.SYSTEM))
3756 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003757 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3758 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003759
3760 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003761 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003762 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3763 /*wipeEuicc=*/ eq(false));
3764 }
3765
3766 public void testWipeEuiccDataEnabled() throws Exception {
3767 setDeviceOwner();
3768 when(getServices().userManager.getUserRestrictionSource(
3769 UserManager.DISALLOW_FACTORY_RESET,
3770 UserHandle.SYSTEM))
3771 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003772 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3773 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003774
3775 dpm.wipeData(WIPE_EUICC);
3776 verify(getServices().recoverySystem).rebootWipeUserData(
3777 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3778 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003779 }
3780
3781 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3782 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003783 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003784 UserManager.DISALLOW_FACTORY_RESET,
3785 UserHandle.SYSTEM))
3786 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003787 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3788 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003789 // The DO is not allowed to wipe the device if the user restriction was set
3790 // by the system
3791 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3792 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003793 }
3794
3795 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3796 final int MANAGED_PROFILE_USER_ID = 15;
3797 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3798 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3799
3800 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003801 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003802 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3803
Pavel Grafov75c0a892017-05-18 17:28:27 +01003804 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003805 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3806 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3807 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3808
3809 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3810 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3811
3812 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3813 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3814 // Failed password attempts on the parent user are taken into account, as there isn't a
3815 // separate work challenge.
3816 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3817 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3818 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3819
3820 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3821 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003822 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003823 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003824 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003825 }
3826
3827 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3828 throws Exception {
3829 final int MANAGED_PROFILE_USER_ID = 15;
3830 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3831 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3832
3833 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003834 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003835 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3836
Pavel Grafov75c0a892017-05-18 17:28:27 +01003837 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003838 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3839 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3840 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3841
3842 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3843 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3844
3845 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3846 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3847 // Failed password attempts on the parent user are taken into account, as there isn't a
3848 // separate work challenge.
3849 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3850 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3851 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3852
3853 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3854 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003855 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003856 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003857 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003858 }
3859
3860 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3861 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003862 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003863 UserManager.DISALLOW_FACTORY_RESET,
3864 UserHandle.SYSTEM))
3865 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3866
3867 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3868
3869 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3870 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3871 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3872 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3873 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3874
3875 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3876 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003877 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003878 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3879 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003880 }
3881
3882 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3883 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003884 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003885 UserManager.DISALLOW_FACTORY_RESET,
3886 UserHandle.SYSTEM))
3887 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3888
3889 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3890
3891 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3892 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3893 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3894 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3895 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3896
3897 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003898 verifyZeroInteractions(getServices().recoverySystem);
3899 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003900 .removeUserEvenWhenDisallowed(anyInt());
3901 }
3902
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003903 public void testGetPermissionGrantState() throws Exception {
3904 final String permission = "some.permission";
3905 final String app1 = "com.example.app1";
3906 final String app2 = "com.example.app2";
3907
Pavel Grafov75c0a892017-05-18 17:28:27 +01003908 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003909 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003910 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003911 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003912 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003913 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3914 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003915 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003916 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003917 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003918 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003919 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003920 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3921
3922 // System can retrieve permission grant state.
3923 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003924 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003925 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3926 dpm.getPermissionGrantState(null, app1, permission));
3927 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3928 dpm.getPermissionGrantState(null, app2, permission));
3929
3930 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003931 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3932 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003933 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3934 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003935
3936 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003937 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3938 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003939 setAsProfileOwner(admin1);
3940 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3941 dpm.getPermissionGrantState(admin1, app1, permission));
3942 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3943 dpm.getPermissionGrantState(admin1, app2, permission));
3944 }
3945
Rubin Xuaab7a412016-12-30 21:13:29 +00003946 public void testResetPasswordWithToken() throws Exception {
3947 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3948 setupDeviceOwner();
3949 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003950 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3951 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3952
Rubin Xuaab7a412016-12-30 21:13:29 +00003953 // test adding a token
3954 final byte[] token = new byte[32];
3955 final long handle = 123456;
3956 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003957 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003958 .thenReturn(handle);
3959 assertTrue(dpm.setResetPasswordToken(admin1, token));
3960
3961 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003962 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003963 .thenReturn(true);
3964 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3965
3966 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003967 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003968 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3969 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003970 eq(UserHandle.USER_SYSTEM)))
3971 .thenReturn(true);
3972 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3973
3974 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003975 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003976 .thenReturn(true);
3977 assertTrue(dpm.clearResetPasswordToken(admin1));
3978 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003979
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01003980 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
3981 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3982 () -> dpm.setPasswordBlacklist(admin1, null, null));
3983 verifyZeroInteractions(getServices().passwordBlacklist);
3984 }
3985
3986 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
3987 setupProfileOwner();
3988 dpm.setPasswordBlacklist(admin1, null, null);
3989 verifyZeroInteractions(getServices().passwordBlacklist);
3990 }
3991
3992 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
3993 final String name = "myblacklist";
3994 final List<String> explicit = Arrays.asList("password", "letmein");
3995 setupProfileOwner();
3996 dpm.setPasswordBlacklist(admin1, name, explicit);
3997 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
3998 }
3999
4000 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4001 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4002 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4003 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4004 setupDeviceOwner();
4005 final String name = "Name of the Blacklist";
4006 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4007 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4008 }
4009
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004010 public void testIsActivePasswordSufficient() throws Exception {
4011 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4012 mContext.packageName = admin1.getPackageName();
4013 setupDeviceOwner();
4014
4015 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4016 dpm.setPasswordMinimumLength(admin1, 8);
4017 dpm.setPasswordMinimumLetters(admin1, 6);
4018 dpm.setPasswordMinimumLowerCase(admin1, 3);
4019 dpm.setPasswordMinimumUpperCase(admin1, 1);
4020 dpm.setPasswordMinimumNonLetter(admin1, 1);
4021 dpm.setPasswordMinimumNumeric(admin1, 1);
4022 dpm.setPasswordMinimumSymbols(admin1, 0);
4023
Rubin Xucc391c22018-01-02 20:37:35 +00004024 reset(mContext.spiedContext);
4025
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004026 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4027 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4028 8, 2,
4029 6, 1,
4030 0, 1);
4031
4032 setActivePasswordState(passwordMetricsNoSymbols);
4033 assertTrue(dpm.isActivePasswordSufficient());
4034
4035 initializeDpms();
4036 reset(mContext.spiedContext);
4037 assertTrue(dpm.isActivePasswordSufficient());
4038
4039 // This call simulates the user entering the password for the first time after a reboot.
4040 // This causes password metrics to be reloaded into memory. Until this happens,
4041 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4042 // even if the DPC changes password requirements so that the password no longer meets the
4043 // requirements. This is a known limitation of the current implementation of
4044 // isActivePasswordSufficient() - see b/34218769.
4045 setActivePasswordState(passwordMetricsNoSymbols);
4046 assertTrue(dpm.isActivePasswordSufficient());
4047
4048 dpm.setPasswordMinimumSymbols(admin1, 1);
4049 // This assertion would fail if we had not called setActivePasswordState() again after
4050 // initializeDpms() - see previous comment.
4051 assertFalse(dpm.isActivePasswordSufficient());
4052
4053 initializeDpms();
4054 reset(mContext.spiedContext);
4055 assertFalse(dpm.isActivePasswordSufficient());
4056
4057 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4058 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4059 7, 2,
4060 5, 1,
4061 1, 2);
4062
4063 setActivePasswordState(passwordMetricsWithSymbols);
4064 assertTrue(dpm.isActivePasswordSufficient());
4065 }
4066
Pavel Grafov75c0a892017-05-18 17:28:27 +01004067 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4068 throws Exception {
4069 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004070 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004071
Pavel Grafov75c0a892017-05-18 17:28:27 +01004072 dpm.setActivePasswordState(passwordMetrics, userHandle);
4073 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004074
Rubin Xucc391c22018-01-02 20:37:35 +00004075 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4076 // reportPasswordChanged()
4077 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4078 MockUtils.checkIntentAction(
4079 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4080 MockUtils.checkUserHandle(userHandle));
4081
Pavel Grafov75c0a892017-05-18 17:28:27 +01004082 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4083 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004084 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004085
4086 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4087 MockUtils.checkIntent(intent),
4088 MockUtils.checkUserHandle(userHandle));
4089
4090 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4091 // let it finish with system uid, otherwise it will throw and crash.
4092 flushTasks();
4093
4094 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004095 }
4096
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004097 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4098 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4099 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4100 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4101 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4102 DpmMockContext.SYSTEM_UID);
4103 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4104 DpmMockContext.SYSTEM_UID);
4105
4106 // Set up a device owner.
4107 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004108 setupDeviceOwner();
4109
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004110 // First and second user set IMEs manually.
4111 mContext.binder.callingUid = firstUserSystemUid;
4112 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4113 mContext.binder.callingUid = secondUserSystemUid;
4114 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004115
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004116 // Device owner changes IME for first user.
4117 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004119 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004120 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004121 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004122 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004124 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4125 mContext.binder.callingUid = firstUserSystemUid;
4126 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4127 mContext.binder.callingUid = secondUserSystemUid;
4128 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004129
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004130 // Second user changes IME manually.
4131 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4132 mContext.binder.callingUid = firstUserSystemUid;
4133 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4134 mContext.binder.callingUid = secondUserSystemUid;
4135 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004136
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004137 // First user changes IME manually.
4138 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4139 mContext.binder.callingUid = firstUserSystemUid;
4140 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4141 mContext.binder.callingUid = secondUserSystemUid;
4142 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004143
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004144 // Device owner changes IME for first user again.
4145 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004146 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004147 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004148 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004149 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004150 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004151 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4152 mContext.binder.callingUid = firstUserSystemUid;
4153 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4154 mContext.binder.callingUid = secondUserSystemUid;
4155 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004156
4157 // Restarting the DPMS should not lose information.
4158 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004159 mContext.binder.callingUid = firstUserSystemUid;
4160 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4161 mContext.binder.callingUid = secondUserSystemUid;
4162 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004163
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004164 // Device owner can find out whether it set the current IME itself.
4165 mContext.binder.callingUid = deviceOwnerUid;
4166 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004167
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004168 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004169 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004170 mContext.binder.callingUid = firstUserSystemUid;
4171 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4172 mContext.binder.callingUid = secondUserSystemUid;
4173 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004174 }
4175
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004176 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4177 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4178 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4179 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4180 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4181 DpmMockContext.SYSTEM_UID);
4182 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4183 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004184
4185 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004186 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004187 setupProfileOwner();
4188
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004189 // First and second user set IMEs manually.
4190 mContext.binder.callingUid = firstUserSystemUid;
4191 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4192 mContext.binder.callingUid = secondUserSystemUid;
4193 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004194
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004195 // Profile owner changes IME for second user.
4196 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004197 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004198 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004199 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004200 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004201 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004202 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004203 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4204 mContext.binder.callingUid = firstUserSystemUid;
4205 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4206 mContext.binder.callingUid = secondUserSystemUid;
4207 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004208
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004209 // First user changes IME manually.
4210 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4211 mContext.binder.callingUid = firstUserSystemUid;
4212 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4213 mContext.binder.callingUid = secondUserSystemUid;
4214 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004215
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004216 // Second user changes IME manually.
4217 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4218 mContext.binder.callingUid = firstUserSystemUid;
4219 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4220 mContext.binder.callingUid = secondUserSystemUid;
4221 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004222
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004223 // Profile owner changes IME for second user again.
4224 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004225 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004226 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004227 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004228 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004229 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004230 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4231 mContext.binder.callingUid = firstUserSystemUid;
4232 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4233 mContext.binder.callingUid = secondUserSystemUid;
4234 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004235
4236 // Restarting the DPMS should not lose information.
4237 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004238 mContext.binder.callingUid = firstUserSystemUid;
4239 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4240 mContext.binder.callingUid = secondUserSystemUid;
4241 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004242
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004243 // Profile owner can find out whether it set the current IME itself.
4244 mContext.binder.callingUid = profileOwnerUid;
4245 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004246
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004247 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004248 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004249 mContext.binder.callingUid = firstUserSystemUid;
4250 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4251 mContext.binder.callingUid = secondUserSystemUid;
4252 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004253 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004254
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004255 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4256 throws Exception {
4257 // Set up a device owner.
4258 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4259 setupDeviceOwner();
4260 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4261 }
4262
4263 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4264 throws Exception {
4265 // Set up a profile owner.
4266 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4267 setupProfileOwner();
4268 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4269 }
4270
4271 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4272 int adminUid) throws Exception {
4273 mContext.binder.callingUid = adminUid;
4274 final int userId = UserHandle.getUserId(adminUid);
4275
4276 final String packageName = "some.package";
4277 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4278 admin1, Collections.singletonList(packageName)));
4279 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4280
4281 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4282 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4283
4284 // Attempt to set to empty list (which means no listener is whitelisted)
4285 mContext.binder.callingUid = adminUid;
4286 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004287 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004288 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4289
4290 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4291 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4292 }
4293
4294 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4295 // Set up a managed profile
4296 final int MANAGED_PROFILE_USER_ID = 15;
4297 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4298 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4299 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4300
4301 final String permittedListener = "some.package";
4302 setupPackageInPackageManager(
4303 permittedListener,
4304 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4305 /*appId=*/ 12345, /*flags=*/ 0);
4306
4307 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4308 admin1, Collections.singletonList(permittedListener)));
4309
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004310 // isNotificationListenerServicePermitted should throw if not called from System.
4311 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4312 () -> dpms.isNotificationListenerServicePermitted(
4313 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004314
4315 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4316 assertTrue(dpms.isNotificationListenerServicePermitted(
4317 permittedListener, MANAGED_PROFILE_USER_ID));
4318 }
4319
4320 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4321 throws Exception {
4322 // Set up a managed profile
4323 final int MANAGED_PROFILE_USER_ID = 15;
4324 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4325 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4326 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4327
4328 final String permittedListener = "permitted.package";
4329 int appId = 12345;
4330 setupPackageInPackageManager(
4331 permittedListener,
4332 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4333 appId, /*flags=*/ 0);
4334
4335 final String notPermittedListener = "not.permitted.package";
4336 setupPackageInPackageManager(
4337 notPermittedListener,
4338 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4339 ++appId, /*flags=*/ 0);
4340
4341 final String systemListener = "system.package";
4342 setupPackageInPackageManager(
4343 systemListener,
4344 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4345 ++appId, ApplicationInfo.FLAG_SYSTEM);
4346
4347 // By default all packages are allowed
4348 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4349
4350 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4351 assertTrue(dpms.isNotificationListenerServicePermitted(
4352 permittedListener, MANAGED_PROFILE_USER_ID));
4353 assertTrue(dpms.isNotificationListenerServicePermitted(
4354 notPermittedListener, MANAGED_PROFILE_USER_ID));
4355 assertTrue(dpms.isNotificationListenerServicePermitted(
4356 systemListener, MANAGED_PROFILE_USER_ID));
4357
4358 // Setting only one package in the whitelist
4359 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4360 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4361 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004362 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004363 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4364 assertEquals(1, permittedListeners.size());
4365 assertEquals(permittedListener, permittedListeners.get(0));
4366
4367 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4368 assertTrue(dpms.isNotificationListenerServicePermitted(
4369 permittedListener, MANAGED_PROFILE_USER_ID));
4370 assertFalse(dpms.isNotificationListenerServicePermitted(
4371 notPermittedListener, MANAGED_PROFILE_USER_ID));
4372 // System packages are always allowed (even if not in the whitelist)
4373 assertTrue(dpms.isNotificationListenerServicePermitted(
4374 systemListener, MANAGED_PROFILE_USER_ID));
4375
4376 // Setting an empty whitelist - only system listeners allowed
4377 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4378 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004379 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004380 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4381
4382 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4383 assertFalse(dpms.isNotificationListenerServicePermitted(
4384 permittedListener, MANAGED_PROFILE_USER_ID));
4385 assertFalse(dpms.isNotificationListenerServicePermitted(
4386 notPermittedListener, MANAGED_PROFILE_USER_ID));
4387 // System packages are always allowed (even if not in the whitelist)
4388 assertTrue(dpms.isNotificationListenerServicePermitted(
4389 systemListener, MANAGED_PROFILE_USER_ID));
4390
4391 // Setting a null whitelist - all listeners allowed
4392 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4393 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4394 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4395
4396 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4397 assertTrue(dpms.isNotificationListenerServicePermitted(
4398 permittedListener, MANAGED_PROFILE_USER_ID));
4399 assertTrue(dpms.isNotificationListenerServicePermitted(
4400 notPermittedListener, MANAGED_PROFILE_USER_ID));
4401 assertTrue(dpms.isNotificationListenerServicePermitted(
4402 systemListener, MANAGED_PROFILE_USER_ID));
4403 }
4404
4405 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4406 throws Exception {
4407 // Set up a managed profile
4408 final int MANAGED_PROFILE_USER_ID = 15;
4409 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4410 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4411 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4412
4413 final String nonSystemPackage = "non.system.package";
4414 int appId = 12345;
4415 setupPackageInPackageManager(
4416 nonSystemPackage,
4417 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4418 appId, /*flags=*/ 0);
4419
4420 final String systemListener = "system.package";
4421 setupPackageInPackageManager(
4422 systemListener,
4423 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4424 ++appId, ApplicationInfo.FLAG_SYSTEM);
4425
4426 // By default all packages are allowed (for all profiles)
4427 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4428
4429 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4430 assertTrue(dpms.isNotificationListenerServicePermitted(
4431 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4432 assertTrue(dpms.isNotificationListenerServicePermitted(
4433 systemListener, MANAGED_PROFILE_USER_ID));
4434 assertTrue(dpms.isNotificationListenerServicePermitted(
4435 nonSystemPackage, UserHandle.USER_SYSTEM));
4436 assertTrue(dpms.isNotificationListenerServicePermitted(
4437 systemListener, UserHandle.USER_SYSTEM));
4438
4439 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4440 // all allowed in primary profile
4441 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4442 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004443 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004444 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4445
4446 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4447 assertFalse(dpms.isNotificationListenerServicePermitted(
4448 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4449 assertTrue(dpms.isNotificationListenerServicePermitted(
4450 systemListener, MANAGED_PROFILE_USER_ID));
4451 assertTrue(dpms.isNotificationListenerServicePermitted(
4452 nonSystemPackage, UserHandle.USER_SYSTEM));
4453 assertTrue(dpms.isNotificationListenerServicePermitted(
4454 systemListener, UserHandle.USER_SYSTEM));
4455 }
4456
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004457 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 mServiceContext.packageName = mRealTestContext.getPackageName();
4459 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4460 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004461 setDeviceOwner();
4462
Pavel Grafov75c0a892017-05-18 17:28:27 +01004463 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004464 }
4465
4466 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004467 mServiceContext.packageName = mRealTestContext.getPackageName();
4468 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4469 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004470 setAsProfileOwner(admin1);
4471
Pavel Grafov75c0a892017-05-18 17:28:27 +01004472 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4473 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004474 }
4475
4476 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004477 mServiceContext.packageName = mRealTestContext.getPackageName();
4478 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4479 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004480 setAsProfileOwner(admin1);
4481
Pavel Grafov75c0a892017-05-18 17:28:27 +01004482 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4483 caller.packageName = "com.example.delegate";
4484 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4485 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004486
Pavel Grafov75c0a892017-05-18 17:28:27 +01004487 // Make caller a delegated cert installer.
4488 runAsCaller(mAdmin1Context, dpms,
4489 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004490
4491 verifyCanGetOwnerInstalledCaCerts(null, caller);
4492 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004493 }
4494
Rubin Xucc391c22018-01-02 20:37:35 +00004495 public void testDisallowSharingIntoProfileSetRestriction() {
4496 Bundle restriction = new Bundle();
4497 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4498
4499 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4500 RestrictionsListener listener = new RestrictionsListener(mContext);
4501 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4502 new Bundle());
4503 verifyDataSharingChangedBroadcast();
4504 }
4505
4506 public void testDisallowSharingIntoProfileClearRestriction() {
4507 Bundle restriction = new Bundle();
4508 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4509
4510 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4511 RestrictionsListener listener = new RestrictionsListener(mContext);
4512 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4513 restriction);
4514 verifyDataSharingChangedBroadcast();
4515 }
4516
4517 public void testDisallowSharingIntoProfileUnchanged() {
4518 RestrictionsListener listener = new RestrictionsListener(mContext);
4519 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4520 new Bundle());
4521 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4522 }
4523
4524 private void verifyDataSharingChangedBroadcast() {
4525 Intent expectedIntent = new Intent(
4526 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4527 expectedIntent.setPackage("com.android.managedprovisioning");
4528 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4529 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4530 MockUtils.checkIntent(expectedIntent),
4531 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4532 }
4533
Robin Lee2c68dad2017-03-17 12:50:24 +00004534 private void verifyCanGetOwnerInstalledCaCerts(
4535 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004536 final String alias = "cert";
4537 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004538
4539 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004540 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004541 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4542 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004543 }
4544 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4545
4546 // caller: device admin or delegated certificate installer
4547 callerContext.applicationInfo = new ApplicationInfo();
4548 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4549
4550 // system_server
4551 final DpmMockContext serviceContext = mContext;
4552 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004553 getServices().addPackageContext(callerUser, admin1Context);
4554 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004555
4556 // Install a CA cert.
4557 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004558 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004559 .thenReturn(alias);
4560 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004561 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004562 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004563 });
4564
Pavel Grafov75c0a892017-05-18 17:28:27 +01004565 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4566 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4567 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004568 flushTasks();
4569
Robin Lee2c68dad2017-03-17 12:50:24 +00004570 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4571
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004572 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004573 runAsCaller(admin1Context, dpms, (dpm) -> {
4574 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004575 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004576 ownerInstalledCaCerts.addAll(installedCaCerts);
4577 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004578
4579 // Restarting the DPMS should not lose information.
4580 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004581 runAsCaller(admin1Context, dpms, (dpm) ->
4582 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004583
4584 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004585 runAsCaller(serviceContext, dpms, (dpm) -> {
4586 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004587
Robin Lee2c68dad2017-03-17 12:50:24 +00004588 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004589 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004590 });
4591
Pavel Grafov75c0a892017-05-18 17:28:27 +01004592 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4593 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4594 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004595 flushTasks();
4596
4597 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4598 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004599 runAsCaller(admin1Context, dpms, (dpm) -> {
4600 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4601 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004602 }
4603
Robin Lee2c68dad2017-03-17 12:50:24 +00004604 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4605 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004606 final String alias = "cert";
4607 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004608
4609 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004610 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004611 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4612 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004613 }
4614 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4615
4616 // caller: device admin or delegated certificate installer
4617 callerContext.applicationInfo = new ApplicationInfo();
4618 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4619
4620 // system_server
4621 final DpmMockContext serviceContext = mContext;
4622 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004623 getServices().addPackageContext(callerUser, admin1Context);
4624 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004625
4626 // Install a CA cert as caller
4627 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004628 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004629 .thenReturn(alias);
4630 assertTrue(dpm.installCaCert(callerName, caCert));
4631 });
4632
4633 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004634 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004635 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004636 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4637 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4638 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004639 flushTasks();
4640
Robin Lee2c68dad2017-03-17 12:50:24 +00004641 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004642 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004643
4644 runAsCaller(serviceContext, dpms, (dpm) -> {
4645 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4646 assertNotNull(ownerInstalledCaCerts);
4647 assertTrue(ownerInstalledCaCerts.isEmpty());
4648 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004649 }
4650
Eran Messeri94d56762017-12-21 20:50:54 +00004651 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4652 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4653 Arrays.sort(gotFlags);
4654 Arrays.sort(expectedFlags);
4655 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4656 }
4657
4658 public void testTranslationOfIdAttestationFlag() {
4659 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4660 int[] correspondingAttUtilsTypes = new int[]{
4661 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4662 AttestationUtils.ID_TYPE_MEID};
4663
4664 // Test translation of zero flags
4665 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4666
4667 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4668 // non-null array
4669 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4670
4671 // Test translation of a single flag
4672 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4673 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4674 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4675
4676 // Test translation of two flags
4677 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4678 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4679 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4680 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4681
4682 // Test translation of all three flags
4683 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4684 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4685 AttestationUtils.ID_TYPE_MEID});
4686 // Test translation of all three flags
4687 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4688 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4689 AttestationUtils.ID_TYPE_MEID});
4690 }
4691
Victor Chang3e794af2016-03-04 13:48:17 +00004692 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004693 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004694 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4695 dpms.notifyChangeToContentObserver(
4696 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4697 }
4698
4699 private void assertProvisioningAllowed(String action, boolean expected) {
4700 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4701 dpm.isProvisioningAllowed(action));
4702 }
Tony Mak2f26b792016-11-28 17:54:51 +00004703
Nicolas Prevot45d29072017-01-18 16:11:19 +00004704 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4705 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004706 final String previousPackageName = mContext.packageName;
4707 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004708
4709 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4710 mContext.packageName = packageName;
4711 mMockContext.binder.callingUid = uid;
4712 assertProvisioningAllowed(action, expected);
4713
4714 // Set the previous package name / calling uid to go back to the initial state.
4715 mContext.packageName = previousPackageName;
4716 mMockContext.binder.callingUid = previousUid;
4717 }
4718
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004719 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004720 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4721 }
4722
4723 private void assertCheckProvisioningPreCondition(
4724 String action, String packageName, int provisioningCondition) {
4725 assertEquals("checkProvisioningPreCondition("
4726 + action + ", " + packageName + ") returning unexpected result",
4727 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004728 }
4729
Tony Mak2f26b792016-11-28 17:54:51 +00004730 /**
4731 * Setup a managed profile with the specified admin and its uid.
4732 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4733 * @param adminUid uid of the admin package.
4734 * @param copyFromAdmin package information for {@code admin} will be built based on this
4735 * component's information.
4736 */
4737 private void addManagedProfile(
4738 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4739 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004740 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004741 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4742 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4743 dpm.setActiveAdmin(admin, false, userId);
4744 assertTrue(dpm.setProfileOwner(admin, null, userId));
4745 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4746 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004747
4748 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004749 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004750 */
Robin Leeabaa0692017-02-20 20:54:22 +00004751 private static StringParceledListSlice asSlice(String[] s) {
4752 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004753 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004754
4755 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004756 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4757 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004758
Robin Lee2c68dad2017-03-17 12:50:24 +00004759 // We can't let exceptions happen on the background thread. Throw them here if they happen
4760 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004761 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004762 }
Victor Chang3e794af2016-03-04 13:48:17 +00004763}