blob: d26a3c7b64d4caa4e26a747d7d762bb8ad850f05 [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);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800189 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700190 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
191 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
192 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800193 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700194
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
196 mAdmin1Context.packageName = admin1.getPackageName();
197 mAdmin1Context.applicationInfo = new ApplicationInfo();
198 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
199
Makoto Onukib643fb02015-09-22 15:03:44 -0700200 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700201 }
202
Robin Lee2c68dad2017-03-17 12:50:24 +0000203 @Override
204 protected void tearDown() throws Exception {
205 flushTasks();
206 super.tearDown();
207 }
208
Makoto Onukia52562c2015-10-01 16:12:31 -0700209 private void initializeDpms() {
210 // Need clearCallingIdentity() to pass permission checks.
211 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100212 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700213
Pavel Grafov75c0a892017-05-18 17:28:27 +0100214 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
215 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 Shankac53c47f2018-01-16 12:01:00 -0800286 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800287 // 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));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800310 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
311 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
312 }
313
314 public void testLoadAdminData_noAdmins() throws Exception {
315 final int ANOTHER_USER_ID = 15;
316 getServices().addUser(ANOTHER_USER_ID, 0);
317
318 initializeDpms();
319
320 // Verify
321 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
322 null, DpmMockContext.CALLER_USER_HANDLE);
323 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
324 null, ANOTHER_USER_ID);
325 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
326 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800327 }
328
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700329 /**
330 * Caller doesn't have proper permissions.
331 */
332 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700333 // 1. Failure cases.
334
335 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100336 assertExpectException(SecurityException.class, /* messageRegex= */ null,
337 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700338
339 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
340 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100341
342 assertExpectException(SecurityException.class, /* messageRegex= */ null,
343 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344 }
345
Makoto Onukif76b06a2015-09-22 15:03:44 -0700346 /**
347 * Test for:
348 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800349 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700350 * {@link DevicePolicyManager#isAdminActive}
351 * {@link DevicePolicyManager#isAdminActiveAsUser}
352 * {@link DevicePolicyManager#getActiveAdmins}
353 * {@link DevicePolicyManager#getActiveAdminsAsUser}
354 */
355 public void testSetActiveAdmin() throws Exception {
356 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700357 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
358
Makoto Onukif76b06a2015-09-22 15:03:44 -0700359 // 2. Call the API.
360 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700361
362 // 3. Verify internal calls.
363
364 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700365 verify(mContext.spiedContext).sendBroadcastAsUser(
366 MockUtils.checkIntentAction(
367 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
368 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
369 verify(mContext.spiedContext).sendBroadcastAsUser(
370 MockUtils.checkIntentAction(
371 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700372 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
373
Pavel Grafov75c0a892017-05-18 17:28:27 +0100374 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375 eq(admin1.getPackageName()),
376 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
377 eq(PackageManager.DONT_KILL_APP),
378 eq(DpmMockContext.CALLER_USER_HANDLE),
379 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700380
Sudheer Shanka101c3532018-01-08 16:28:42 -0800381 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
382 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
383
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700384 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700385
386 // Make sure it's active admin1.
387 assertTrue(dpm.isAdminActive(admin1));
388 assertFalse(dpm.isAdminActive(admin2));
389 assertFalse(dpm.isAdminActive(admin3));
390
391 // But not admin1 for a different user.
392
393 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
394 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
395 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
396
397 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
398 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
399
400 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
401
402 // Next, add one more admin.
403 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700404 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700405 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700406
407 dpm.setActiveAdmin(admin2, /* replace =*/ false);
408
409 // Now we have two admins.
410 assertTrue(dpm.isAdminActive(admin1));
411 assertTrue(dpm.isAdminActive(admin2));
412 assertFalse(dpm.isAdminActive(admin3));
413
414 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
415 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100416 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700417 eq(admin1.getPackageName()),
418 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
419 eq(PackageManager.DONT_KILL_APP),
420 eq(DpmMockContext.CALLER_USER_HANDLE),
421 anyString());
422
Sudheer Shanka101c3532018-01-08 16:28:42 -0800423 // times(2) because it was previously called for admin1 which is in the same package
424 // as admin2.
425 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
426 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
427
Makoto Onukif76b06a2015-09-22 15:03:44 -0700428 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100429 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
430 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431
432 // 5. Add the same admin1 again with replace, which should succeed.
433 dpm.setActiveAdmin(admin1, /* replace =*/ true);
434
435 // TODO make sure it's replaced.
436
437 // 6. Test getActiveAdmins()
438 List<ComponentName> admins = dpm.getActiveAdmins();
439 assertEquals(2, admins.size());
440 assertEquals(admin1, admins.get(0));
441 assertEquals(admin2, admins.get(1));
442
Sudheer Shanka101c3532018-01-08 16:28:42 -0800443 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
444 // replaced
445 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
446
Makoto Onukif76b06a2015-09-22 15:03:44 -0700447 // Another user has no admins.
448 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
449
450 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
451 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
452
453 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
454 }
455
Makoto Onukid932f762015-09-29 16:53:38 -0700456 public void testSetActiveAdmin_multiUsers() throws Exception {
457
458 final int ANOTHER_USER_ID = 100;
459 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
460
Pavel Grafov75c0a892017-05-18 17:28:27 +0100461 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700462
463 // Set up pacakge manager for the other user.
464 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700465
466 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
467
468 dpm.setActiveAdmin(admin1, /* replace =*/ false);
469
470 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
471 dpm.setActiveAdmin(admin2, /* replace =*/ false);
472
473
474 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
475 assertTrue(dpm.isAdminActive(admin1));
476 assertFalse(dpm.isAdminActive(admin2));
477
478 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
479 assertFalse(dpm.isAdminActive(admin1));
480 assertTrue(dpm.isAdminActive(admin2));
481 }
482
Makoto Onukif76b06a2015-09-22 15:03:44 -0700483 /**
484 * Test for:
485 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800486 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700487 */
488 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
489 // 1. Make sure the caller has proper permissions.
490 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
491
492 dpm.setActiveAdmin(admin1, /* replace =*/ false);
493 assertTrue(dpm.isAdminActive(admin1));
494
495 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100496 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
497 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700498 }
499
500 /**
501 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800502 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
503 * BIND_DEVICE_ADMIN.
504 */
505 public void testSetActiveAdmin_permissionCheck() throws Exception {
506 // 1. Make sure the caller has proper permissions.
507 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
508
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100509 assertExpectException(IllegalArgumentException.class,
510 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
511 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800512 assertFalse(dpm.isAdminActive(adminNoPerm));
513
514 // Change the target API level to MNC. Now it can be set as DA.
515 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
516 VERSION_CODES.M);
517 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
518 assertTrue(dpm.isAdminActive(adminNoPerm));
519
520 // TODO Test the "load from the file" case where DA will still be loaded even without
521 // BIND_DEVICE_ADMIN and target API is N.
522 }
523
524 /**
525 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700526 * {@link DevicePolicyManager#removeActiveAdmin}
527 */
528 public void testRemoveActiveAdmin_SecurityException() {
529 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
530
531 // Add admin.
532
533 dpm.setActiveAdmin(admin1, /* replace =*/ false);
534
535 assertTrue(dpm.isAdminActive(admin1));
536
537 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
538
539 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100540 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
541 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700542
543 // Try to remove active admin with a different caller userid should fail too, without
544 // having MANAGE_DEVICE_ADMINS.
545 mContext.callerPermissions.clear();
546
Makoto Onukid932f762015-09-29 16:53:38 -0700547 // Change the caller, and call into DPMS directly with a different user-id.
548
Makoto Onukif76b06a2015-09-22 15:03:44 -0700549 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100550 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
551 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552 }
553
554 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800555 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
556 * (because we can't send the remove broadcast).
557 */
558 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
559 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
560
561 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
562
563 // Add admin.
564
565 dpm.setActiveAdmin(admin1, /* replace =*/ false);
566
567 assertTrue(dpm.isAdminActive(admin1));
568
569 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
570
571 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100572 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800573 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100574 assertExpectException(IllegalStateException.class,
575 /* messageRegex= */ "User must be running and unlocked",
576 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800577
578 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800579 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
580 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800581
582 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100583 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800584 .thenReturn(true);
585
586 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700587 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800588 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
589 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590 }
591
592 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700593 * Test for:
594 * {@link DevicePolicyManager#removeActiveAdmin}
595 */
Makoto Onukid932f762015-09-29 16:53:38 -0700596 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700597 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
598
599 // Add admin1.
600
601 dpm.setActiveAdmin(admin1, /* replace =*/ false);
602
603 assertTrue(dpm.isAdminActive(admin1));
604 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
605
606 // Different user, but should work, because caller has proper permissions.
607 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700608
609 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700610 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700611
612 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700613 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800614 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
615 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700616
617 // TODO DO Still can't be removed in this case.
618 }
619
620 /**
621 * Test for:
622 * {@link DevicePolicyManager#removeActiveAdmin}
623 */
624 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
625 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
626 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
627
628 // Add admin1.
629
630 dpm.setActiveAdmin(admin1, /* replace =*/ false);
631
632 assertTrue(dpm.isAdminActive(admin1));
633 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
634
635 // Broadcast from saveSettingsLocked().
636 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
637 MockUtils.checkIntentAction(
638 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
639 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
640
641 // Remove. No permissions, but same user, so it'll work.
642 mContext.callerPermissions.clear();
643 dpm.removeActiveAdmin(admin1);
644
Makoto Onukif76b06a2015-09-22 15:03:44 -0700645 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
646 MockUtils.checkIntentAction(
647 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
648 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
649 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700650 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700651 eq(dpms.mHandler),
652 eq(Activity.RESULT_OK),
653 isNull(String.class),
654 isNull(Bundle.class));
655
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700656 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800657 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
658 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659
660 // Again broadcast from saveSettingsLocked().
661 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
662 MockUtils.checkIntentAction(
663 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
664 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
665
666 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700667 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700668
Sudheer Shanka101c3532018-01-08 16:28:42 -0800669 public void testRemoveActiveAdmin_multipleAdminsInUser() {
670 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
671 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
672
673 // Add admin1.
674 dpm.setActiveAdmin(admin1, /* replace =*/ false);
675
676 assertTrue(dpm.isAdminActive(admin1));
677 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
678
679 // Add admin2.
680 dpm.setActiveAdmin(admin2, /* replace =*/ false);
681
682 assertTrue(dpm.isAdminActive(admin2));
683 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
684
685 // Broadcast from saveSettingsLocked().
686 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
687 MockUtils.checkIntentAction(
688 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
689 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
690
691 // Remove. No permissions, but same user, so it'll work.
692 mContext.callerPermissions.clear();
693 dpm.removeActiveAdmin(admin1);
694
695 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
696 MockUtils.checkIntentAction(
697 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
698 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
699 isNull(String.class),
700 any(BroadcastReceiver.class),
701 eq(dpms.mHandler),
702 eq(Activity.RESULT_OK),
703 isNull(String.class),
704 isNull(Bundle.class));
705
706 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
707 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
708 MockUtils.checkAdminApps(admin2.getPackageName()),
709 eq(DpmMockContext.CALLER_USER_HANDLE));
710
711 // Again broadcast from saveSettingsLocked().
712 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
713 MockUtils.checkIntentAction(
714 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
715 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
716 }
717
718 /**
719 * Test for:
720 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
721 */
722 public void testForceRemoveActiveAdmin() throws Exception {
723 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
724
725 // Add admin.
726 setupPackageInPackageManager(admin1.getPackageName(),
727 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
728 /* appId= */ 10138,
729 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
730 dpm.setActiveAdmin(admin1, /* replace =*/ false);
731 assertTrue(dpm.isAdminActive(admin1));
732
733 // Calling from a non-shell uid should fail with a SecurityException
734 mContext.binder.callingUid = 123456;
735 assertExpectException(SecurityException.class,
736 /* messageRegex =*/ "Non-shell user attempted to call",
737 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
738
739 mContext.binder.callingUid = Process.SHELL_UID;
740 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
741
742 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
743 // Verify
744 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
745 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
746 null, DpmMockContext.CALLER_USER_HANDLE);
747 }
748
Makoto Onukib643fb02015-09-22 15:03:44 -0700749 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000750 * Test for: @{link DevicePolicyManager#setActivePasswordState}
751 *
752 * Validates that when the password for a user changes, the notification broadcast intent
753 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
754 * addition to ones in the original user.
755 */
756 public void testSetActivePasswordState_sendToProfiles() throws Exception {
757 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
758
759 final int MANAGED_PROFILE_USER_ID = 78;
760 final int MANAGED_PROFILE_ADMIN_UID =
761 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
762
763 // Setup device owner.
764 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
765 mContext.packageName = admin1.getPackageName();
766 setupDeviceOwner();
767
768 // Add a managed profile belonging to the system user.
769 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
770
771 // Change the parent user's password.
772 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
773
774 // Both the device owner and the managed profile owner should receive this broadcast.
775 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
776 intent.setComponent(admin1);
777 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
778
779 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
780 MockUtils.checkIntent(intent),
781 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
782 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
783 MockUtils.checkIntent(intent),
784 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
785 }
786
787 /**
788 * Test for: @{link DevicePolicyManager#setActivePasswordState}
789 *
790 * Validates that when the password for a managed profile changes, the notification broadcast
791 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
792 * its parent.
793 */
794 public void testSetActivePasswordState_notSentToParent() throws Exception {
795 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
796
797 final int MANAGED_PROFILE_USER_ID = 78;
798 final int MANAGED_PROFILE_ADMIN_UID =
799 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
800
801 // Setup device owner.
802 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
803 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100804 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000805 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
806 setupDeviceOwner();
807
808 // Add a managed profile belonging to the system user.
809 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
810
811 // Change the profile's password.
812 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
813
814 // Both the device owner and the managed profile owner should receive this broadcast.
815 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
816 intent.setComponent(admin1);
817 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
818
819 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
820 MockUtils.checkIntent(intent),
821 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
822 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
823 MockUtils.checkIntent(intent),
824 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
825 }
826 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000827 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700828 */
829 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000830 setDeviceOwner();
831
832 // Try to set a profile owner on the same user, which should fail.
833 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
834 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100835 assertExpectException(IllegalStateException.class,
836 /* messageRegex= */ "already has a device owner",
837 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000838
839 // DO admin can't be deactivated.
840 dpm.removeActiveAdmin(admin1);
841 assertTrue(dpm.isAdminActive(admin1));
842
843 // TODO Test getDeviceOwnerName() too. To do so, we need to change
844 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
845 }
846
847 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700848 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800849 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700850 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
851 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
852
Makoto Onukid932f762015-09-29 16:53:38 -0700853 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700854 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
855
Makoto Onukid932f762015-09-29 16:53:38 -0700856 // Make sure admin1 is installed on system user.
857 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700858
Makoto Onukic8a5a552015-11-19 14:29:12 -0800859 // Check various get APIs.
860 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
861
Makoto Onukib643fb02015-09-22 15:03:44 -0700862 // DO needs to be an DA.
863 dpm.setActiveAdmin(admin1, /* replace =*/ false);
864
865 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700866 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700867
Makoto Onukic8a5a552015-11-19 14:29:12 -0800868 // getDeviceOwnerComponent should return the admin1 component.
869 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
870 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
871
872 // Check various get APIs.
873 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
874
875 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
876 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
877 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
878 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
879
880 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
881
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000882 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100883 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000884 eq(admin1.getPackageName()));
885
Makoto Onukib643fb02015-09-22 15:03:44 -0700886 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100887 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700888 eq(UserHandle.USER_SYSTEM), eq(false));
889
890 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
891 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
892 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
893
Makoto Onukic8a5a552015-11-19 14:29:12 -0800894 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700895 }
896
Makoto Onukic8a5a552015-11-19 14:29:12 -0800897 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
898 final int origCallingUser = mContext.binder.callingUid;
899 final List origPermissions = new ArrayList(mContext.callerPermissions);
900 mContext.callerPermissions.clear();
901
902 mContext.callerPermissions.add(permission.MANAGE_USERS);
903
904 mContext.binder.callingUid = Process.SYSTEM_UID;
905
906 // TODO Test getDeviceOwnerName() too. To do so, we need to change
907 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
908 if (hasDeviceOwner) {
909 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
910 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
911 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
912
913 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
914 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
915 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
916 } else {
917 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
918 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
919 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
920
921 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
922 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
923 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
924 }
925
926 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
927 if (hasDeviceOwner) {
928 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
929 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
930 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
931
932 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
933 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
934 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
935 } else {
936 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
937 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
938 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
939
940 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
941 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
942 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
943 }
944
945 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
946 // Still with MANAGE_USERS.
947 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
948 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
949 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
950
951 if (hasDeviceOwner) {
952 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
953 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
954 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
955 } else {
956 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
957 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
958 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
959 }
960
961 mContext.binder.callingUid = Process.SYSTEM_UID;
962 mContext.callerPermissions.remove(permission.MANAGE_USERS);
963 // System can still call "OnAnyUser" without MANAGE_USERS.
964 if (hasDeviceOwner) {
965 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
966 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
967 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
968
969 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
970 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
971 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
972 } else {
973 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
974 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
975 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
976
977 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
978 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
979 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
980 }
981
982 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
983 // Still no MANAGE_USERS.
984 if (hasDeviceOwner) {
985 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
986 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
987 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
988 } else {
989 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
990 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
991 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
992 }
993
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100994 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
995 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
996 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
997 dpm::getDeviceOwnerComponentOnAnyUser);
998 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
999 dpm::getDeviceOwnerUserId);
1000 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1001 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001002
1003 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1004 // Still no MANAGE_USERS.
1005 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1006 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1007 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1008
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001009 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1010 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1011 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1012 dpm::getDeviceOwnerComponentOnAnyUser);
1013 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1014 dpm::getDeviceOwnerUserId);
1015 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1016 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001017
1018 // Restore.
1019 mContext.binder.callingUid = origCallingUser;
1020 mContext.callerPermissions.addAll(origPermissions);
1021 }
1022
1023
Makoto Onukib643fb02015-09-22 15:03:44 -07001024 /**
1025 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1026 */
1027 public void testSetDeviceOwner_noSuchPackage() {
1028 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001029 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001030 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1031 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1032
1033 // Call from a process on the system user.
1034 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1035
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001036 assertExpectException(IllegalArgumentException.class,
1037 /* messageRegex= */ "Invalid component",
1038 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001039 }
1040
1041 public void testSetDeviceOwner_failures() throws Exception {
1042 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1043 }
1044
Makoto Onukia52562c2015-10-01 16:12:31 -07001045 public void testClearDeviceOwner() throws Exception {
1046 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001047 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001048 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1049 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1050
1051 // Set admin1 as a DA to the secondary user.
1052 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1053
1054 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1055
1056 // Set admin 1 as the DO to the system user.
1057
1058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1059 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1060 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1061 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1062
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001063 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001064 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001065 eq(admin1.getPackageName()));
1066
Makoto Onukic8a5a552015-11-19 14:29:12 -08001067 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001068
Makoto Onuki90b89652016-01-28 14:44:18 -08001069 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001070 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001071 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001072
1073 assertTrue(dpm.isAdminActive(admin1));
1074 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1075
Makoto Onukia52562c2015-10-01 16:12:31 -07001076 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001077 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001078
1079 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001080 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1081 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001082
1083 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001084 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001085 assertExpectException(IllegalStateException.class,
1086 /* messageRegex= */ "User must be running and unlocked",
1087 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001088
Pavel Grafov75c0a892017-05-18 17:28:27 +01001089 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1090 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001091 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1092
1093 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001094 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001095
Pavel Grafov75c0a892017-05-18 17:28:27 +01001096 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001097 eq(false),
1098 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1099
Pavel Grafov75c0a892017-05-18 17:28:27 +01001100 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001101 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001102 eq(null),
1103 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001104
Sudheer Shanka101c3532018-01-08 16:28:42 -08001105 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1106 null, UserHandle.USER_SYSTEM);
1107
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001108 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001109
1110 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1111 // and once for clearing it.
1112 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1113 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1114 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001115 // TODO Check other calls.
1116 }
1117
1118 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1119 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001121 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1122 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1123
1124 // Set admin1 as a DA to the secondary user.
1125 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1126
1127 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1128
1129 // Set admin 1 as the DO to the system user.
1130
1131 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1132 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1133 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1134 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1135
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001136 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001137 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001138 eq(admin1.getPackageName()));
1139
Makoto Onukic8a5a552015-11-19 14:29:12 -08001140 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001141
1142 // Now call clear from the secondary user, which should throw.
1143 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1144
1145 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001146 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001147 eq(admin1.getPackageName()),
1148 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001149 assertExpectException(SecurityException.class,
1150 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1151 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001152
Makoto Onukic8a5a552015-11-19 14:29:12 -08001153 // DO shouldn't be removed.
1154 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001155 }
1156
Makoto Onukib643fb02015-09-22 15:03:44 -07001157 public void testSetProfileOwner() throws Exception {
1158 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001159
Makoto Onuki90b89652016-01-28 14:44:18 -08001160 // PO admin can't be deactivated.
1161 dpm.removeActiveAdmin(admin1);
1162 assertTrue(dpm.isAdminActive(admin1));
1163
Makoto Onuki803d6752015-10-30 12:58:39 -07001164 // Try setting DO on the same user, which should fail.
1165 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001166 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1167 runAsCaller(mServiceContext, dpms, dpm -> {
1168 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001169 assertExpectException(IllegalStateException.class,
1170 /* messageRegex= */ "already has a profile owner",
1171 () -> dpm.setDeviceOwner(admin2, "owner-name",
1172 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001173 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001174 }
1175
Makoto Onuki90b89652016-01-28 14:44:18 -08001176 public void testClearProfileOwner() throws Exception {
1177 setAsProfileOwner(admin1);
1178
1179 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1180
1181 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1182 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1183
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001184 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001185 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001186 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001187 assertExpectException(IllegalStateException.class,
1188 /* messageRegex= */ "User must be running and unlocked",
1189 () -> dpm.clearProfileOwner(admin1));
1190
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001191 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001192 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001193 dpm.clearProfileOwner(admin1);
1194
1195 // Check
1196 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001197 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001198 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1199 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001200 }
1201
Makoto Onukib643fb02015-09-22 15:03:44 -07001202 public void testSetProfileOwner_failures() throws Exception {
1203 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1204 }
1205
Makoto Onukia52562c2015-10-01 16:12:31 -07001206 public void testGetDeviceOwnerAdminLocked() throws Exception {
1207 checkDeviceOwnerWithMultipleDeviceAdmins();
1208 }
1209
1210 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1211 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1212 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1213 // make sure it gets the right component from the right user.
1214
1215 final int ANOTHER_USER_ID = 100;
1216 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1217
Pavel Grafov75c0a892017-05-18 17:28:27 +01001218 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001219
1220 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001221 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001222 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1223 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1224
1225 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1226
Pavel Grafov75c0a892017-05-18 17:28:27 +01001227 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001228
Makoto Onukia52562c2015-10-01 16:12:31 -07001229 // Make sure the admin packge is installed to each user.
1230 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1231 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1232
1233 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1234 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1235
1236 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1237
1238
1239 // Set active admins to the users.
1240 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1241 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1242
1243 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1244 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1245
1246 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1247
1248 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001249 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001250 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1251
Makoto Onukic8a5a552015-11-19 14:29:12 -08001252 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001253
1254 // Then check getDeviceOwnerAdminLocked().
1255 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1256 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1257 }
1258
1259 /**
1260 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001261 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1262 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001263 *
1264 * We didn't use to persist the DO component class name, but now we do, and the above method
1265 * finds the right component from a package name upon migration.
1266 */
1267 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001268 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001269 checkDeviceOwnerWithMultipleDeviceAdmins();
1270
1271 // Overwrite the device owner setting and clears the clas name.
1272 dpms.mOwners.setDeviceOwner(
1273 new ComponentName(admin2.getPackageName(), ""),
1274 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1275 dpms.mOwners.writeDeviceOwner();
1276
1277 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001278 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001279
1280 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001281 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001282 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001283 initializeDpms();
1284
1285 // Now the DO component name is a full name.
1286 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1287 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001288 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001289 }
1290
Makoto Onukib643fb02015-09-22 15:03:44 -07001291 public void testSetGetApplicationRestriction() {
1292 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001293 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001294
1295 {
1296 Bundle rest = new Bundle();
1297 rest.putString("KEY_STRING", "Foo1");
1298 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1299 }
1300
1301 {
1302 Bundle rest = new Bundle();
1303 rest.putString("KEY_STRING", "Foo2");
1304 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1305 }
1306
1307 {
1308 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1309 assertNotNull(returned);
1310 assertEquals(returned.size(), 1);
1311 assertEquals(returned.get("KEY_STRING"), "Foo1");
1312 }
1313
1314 {
1315 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1316 assertNotNull(returned);
1317 assertEquals(returned.size(), 1);
1318 assertEquals(returned.get("KEY_STRING"), "Foo2");
1319 }
1320
1321 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1322 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1323 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001324
Edman Anjosf9946772016-11-28 16:35:15 +01001325 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001326 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1327 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001328 *
1329 * @param packageName the name of the package to be setup
1330 * @param appId the application ID to be given to the package
1331 * @return the UID of the package as known by the mock package manager
1332 */
1333 private int setupPackageInPackageManager(final String packageName, final int appId)
1334 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001335 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001336 ApplicationInfo.FLAG_HAS_CODE);
1337 }
1338
1339 /**
1340 * Setup a package in the package manager mock. Useful for faking installed applications.
1341 *
1342 * @param packageName the name of the package to be setup
1343 * @param userId the user id where the package will be "installed"
1344 * @param appId the application ID to be given to the package
1345 * @param flags flags to set in the ApplicationInfo for this package
1346 * @return the UID of the package as known by the mock package manager
1347 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001348 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1349 int flags) throws Exception {
1350 final int uid = UserHandle.getUid(userId, appId);
1351 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001352 final PackageInfo pi = new PackageInfo();
1353 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001354 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001355 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001356 eq(packageName),
1357 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001358 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001359 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001360 eq(packageName),
1361 anyInt(),
1362 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001363 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001364 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001365 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001366 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001367 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001368 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001369 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001370 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001371 return uid;
1372 }
1373
Robin Lee7f5c91c2017-02-08 21:27:02 +00001374 public void testCertificateDisclosure() throws Exception {
1375 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1376 final UserHandle user = UserHandle.of(userId);
1377
1378 mContext.applicationInfo = new ApplicationInfo();
1379 mContext.callerPermissions.add(permission.MANAGE_USERS);
1380 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001382 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1383
Robin Leeabaa0692017-02-20 20:54:22 +00001384 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1385 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001386
1387 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1388 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1389
1390 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001391 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001392 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001393 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001394 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001395 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001396 .cancelAsUser(anyString(), anyInt(), eq(user));
1397
1398 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001399 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001400 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001401 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1402 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001403 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001404 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001405 .notifyAsUser(anyString(), anyInt(), argThat(
1406 new BaseMatcher<Notification>() {
1407 @Override
1408 public boolean matches(Object item) {
1409 final Notification noti = (Notification) item;
1410 return TEST_STRING.equals(
1411 noti.extras.getString(Notification.EXTRA_TITLE));
1412 }
1413 @Override
1414 public void describeTo(Description description) {
1415 description.appendText(
1416 "Notification{title=\"" + TEST_STRING + "\"}");
1417 }
1418 }), eq(user));
1419 }
1420
Edman Anjosf9946772016-11-28 16:35:15 +01001421 /**
1422 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1423 * privileges can acually be exercised by a delegate are not covered here.
1424 */
1425 public void testDelegation() throws Exception {
1426 setAsProfileOwner(admin1);
1427
1428 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1429
1430 // Given two packages
1431 final String CERT_DELEGATE = "com.delegate.certs";
1432 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1433 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1434 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1435 20989);
1436
1437 // On delegation
1438 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1439 mContext.packageName = admin1.getPackageName();
1440 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1441 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1442
1443 // DPMS correctly stores and retrieves the delegates
1444 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1445 assertEquals(2, policy.mDelegationMap.size());
1446 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1447 DELEGATION_CERT_INSTALL);
1448 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1449 DELEGATION_CERT_INSTALL);
1450 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1451 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1452 DELEGATION_APP_RESTRICTIONS);
1453 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1454 DELEGATION_APP_RESTRICTIONS);
1455 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1456
1457 // On calling install certificate APIs from an unauthorized process
1458 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1459 mContext.packageName = RESTRICTIONS_DELEGATE;
1460
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001461 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1462 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001463
1464 // On calling install certificate APIs from an authorized process
1465 mContext.binder.callingUid = CERT_DELEGATE_UID;
1466 mContext.packageName = CERT_DELEGATE;
1467
1468 // DPMS executes without a SecurityException
1469 try {
1470 dpm.installCaCert(null, null);
1471 } catch (SecurityException unexpected) {
1472 fail("Threw SecurityException on authorized access");
1473 } catch (NullPointerException expected) {
1474 }
1475
1476 // On removing a delegate
1477 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1478 mContext.packageName = admin1.getPackageName();
1479 dpm.setCertInstallerPackage(admin1, null);
1480
1481 // DPMS does not allow access to ex-delegate
1482 mContext.binder.callingUid = CERT_DELEGATE_UID;
1483 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001484 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1485 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001486
1487 // But still allows access to other existing delegates
1488 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1489 mContext.packageName = RESTRICTIONS_DELEGATE;
1490 try {
1491 dpm.getApplicationRestrictions(null, "pkg");
1492 } catch (SecurityException expected) {
1493 fail("Threw SecurityException on authorized access");
1494 }
1495 }
1496
Esteban Talaverabf60f722015-12-10 16:26:44 +00001497 public void testApplicationRestrictionsManagingApp() throws Exception {
1498 setAsProfileOwner(admin1);
1499
Rubin Xued1928a2016-02-11 17:23:06 +00001500 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001501 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001502 final String nonDelegateExceptionMessageRegex =
1503 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001504 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001505 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1506 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001507
Esteban Talaverabf60f722015-12-10 16:26:44 +00001508 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1509 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001510 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1511 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001513 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001514 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001515 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1516 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001517
1518 // Check via the profile owner that no restrictions were set.
1519 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001520 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001521 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1522
Rubin Xued1928a2016-02-11 17:23:06 +00001523 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001524 assertExpectException(PackageManager.NameNotFoundException.class,
1525 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1526 () -> dpm.setApplicationRestrictionsManagingPackage(
1527 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001528
Esteban Talaverabf60f722015-12-10 16:26:44 +00001529 // Let appRestrictionsManagerPackage manage app restrictions
1530 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1531 assertEquals(appRestrictionsManagerPackage,
1532 dpm.getApplicationRestrictionsManagingPackage(admin1));
1533
1534 // Now that package should be able to set and retrieve app restrictions.
1535 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001536 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001537 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1538 dpm.setApplicationRestrictions(null, "pkg1", rest);
1539 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1540 assertEquals(1, returned.size(), 1);
1541 assertEquals("Foo1", returned.get("KEY_STRING"));
1542
1543 // The same app running on a separate user shouldn't be able to manage app restrictions.
1544 mContext.binder.callingUid = UserHandle.getUid(
1545 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1546 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001547 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1548 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001549
1550 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1551 // too.
1552 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001553 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001554 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1555 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1556 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1557
1558 // Removing the ability for the package to manage app restrictions.
1559 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1560 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1561 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001562 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001563 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001564 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1565 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001566 }
1567
Makoto Onukia4f11972015-10-01 13:19:58 -07001568 public void testSetUserRestriction_asDo() throws Exception {
1569 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001570 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001571 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1572 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1573
1574 // First, set DO.
1575
1576 // Call from a process on the system user.
1577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1578
1579 // Make sure admin1 is installed on system user.
1580 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001581
1582 // Call.
1583 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001584 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001585 UserHandle.USER_SYSTEM));
1586
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001587 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001588 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001589 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001590 DpmTestUtils.assertRestrictions(
1591 DpmTestUtils.newRestrictions(defaultRestrictions),
1592 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1593 );
1594 DpmTestUtils.assertRestrictions(
1595 DpmTestUtils.newRestrictions(defaultRestrictions),
1596 dpm.getUserRestrictions(admin1)
1597 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001598 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001599 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001600 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 eq(true) /* isDeviceOwner */,
1602 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001603 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001604 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001605
1606 for (String restriction : defaultRestrictions) {
1607 dpm.clearUserRestriction(admin1, restriction);
1608 }
1609
Esteban Talavera548a04b2016-12-20 15:22:30 +00001610 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001611 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612
1613 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001614 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001615 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001616 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1617 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001618 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619
Makoto Onukia4f11972015-10-01 13:19:58 -07001620 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001621 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001623 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1624 UserManager.DISALLOW_ADD_USER),
1625 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001627
Makoto Onuki068c54a2015-10-13 14:34:03 -07001628 DpmTestUtils.assertRestrictions(
1629 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001631 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1632 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001633 DpmTestUtils.assertRestrictions(
1634 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001635 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001636 dpm.getUserRestrictions(admin1)
1637 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001638
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001640 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001641 eq(UserHandle.USER_SYSTEM),
1642 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001643 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001644 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001645
Makoto Onuki068c54a2015-10-13 14:34:03 -07001646 DpmTestUtils.assertRestrictions(
1647 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1648 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1649 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001650 DpmTestUtils.assertRestrictions(
1651 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1652 dpm.getUserRestrictions(admin1)
1653 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001654
1655 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001656 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 eq(UserHandle.USER_SYSTEM),
1658 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001659 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001660 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001661
Esteban Talavera548a04b2016-12-20 15:22:30 +00001662 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001663
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001664 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1665 // DO sets them, the scope is global.
1666 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001667 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001669 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001672 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1673 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001674 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675
1676 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1677 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001678 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679
1680 // More tests.
1681 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001682 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1685 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687
1688 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001692 UserManager.DISALLOW_ADD_USER),
1693 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001694 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001695
1696 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 eq(UserHandle.USER_SYSTEM),
1699 // DISALLOW_CAMERA will be applied to both local and global.
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_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001704
1705 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1706 // locally.
1707 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001708 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709
1710 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1711 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1712 dpm.setCameraDisabled(admin2, true);
1713
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001716 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001718 UserManager.DISALLOW_ADD_USER),
1719 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001720 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001721 // TODO Make sure restrictions are written to the file.
1722 }
1723
1724 public void testSetUserRestriction_asPo() {
1725 setAsProfileOwner(admin1);
1726
Makoto Onuki068c54a2015-10-13 14:34:03 -07001727 DpmTestUtils.assertRestrictions(
1728 DpmTestUtils.newRestrictions(),
1729 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1730 .ensureUserRestrictions()
1731 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001732
1733 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001734 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001735 eq(DpmMockContext.CALLER_USER_HANDLE),
1736 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001737 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001738 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739
Makoto Onukia4f11972015-10-01 13:19:58 -07001740 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742 eq(DpmMockContext.CALLER_USER_HANDLE),
1743 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1744 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001745 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001746 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001747
Makoto Onuki068c54a2015-10-13 14:34:03 -07001748 DpmTestUtils.assertRestrictions(
1749 DpmTestUtils.newRestrictions(
1750 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1751 UserManager.DISALLOW_OUTGOING_CALLS
1752 ),
1753 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1754 .ensureUserRestrictions()
1755 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(
1758 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1759 UserManager.DISALLOW_OUTGOING_CALLS
1760 ),
1761 dpm.getUserRestrictions(admin1)
1762 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001763
1764 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001765 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001766 eq(DpmMockContext.CALLER_USER_HANDLE),
1767 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001768 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001770
1771 DpmTestUtils.assertRestrictions(
1772 DpmTestUtils.newRestrictions(
1773 UserManager.DISALLOW_OUTGOING_CALLS
1774 ),
1775 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1776 .ensureUserRestrictions()
1777 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001778 DpmTestUtils.assertRestrictions(
1779 DpmTestUtils.newRestrictions(
1780 UserManager.DISALLOW_OUTGOING_CALLS
1781 ),
1782 dpm.getUserRestrictions(admin1)
1783 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001784
1785 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001786 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001787 eq(DpmMockContext.CALLER_USER_HANDLE),
1788 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001789 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001791
Makoto Onuki068c54a2015-10-13 14:34:03 -07001792 DpmTestUtils.assertRestrictions(
1793 DpmTestUtils.newRestrictions(),
1794 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1795 .ensureUserRestrictions()
1796 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001797 DpmTestUtils.assertRestrictions(
1798 DpmTestUtils.newRestrictions(),
1799 dpm.getUserRestrictions(admin1)
1800 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001801
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001802 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1803 // though when DO sets them they'll be applied globally.
1804 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001805 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001806 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808 eq(DpmMockContext.CALLER_USER_HANDLE),
1809 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1810 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001813
1814 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001815 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001816 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001817 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001818 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001819 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001820 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001821
Makoto Onukia4f11972015-10-01 13:19:58 -07001822 // TODO Make sure restrictions are written to the file.
1823 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001824
Esteban Talavera548a04b2016-12-20 15:22:30 +00001825
1826 public void testDefaultEnabledUserRestrictions() throws Exception {
1827 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1828 mContext.callerPermissions.add(permission.MANAGE_USERS);
1829 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1830 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1831
1832 // First, set DO.
1833
1834 // Call from a process on the system user.
1835 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1836
1837 // Make sure admin1 is installed on system user.
1838 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1839
1840 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1841 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1842 UserHandle.USER_SYSTEM));
1843
1844 // Check that the user restrictions that are enabled by default are set. Then unset them.
1845 String[] defaultRestrictions = UserRestrictionsUtils
1846 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1847 assertTrue(defaultRestrictions.length > 0);
1848 DpmTestUtils.assertRestrictions(
1849 DpmTestUtils.newRestrictions(defaultRestrictions),
1850 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1851 );
1852 DpmTestUtils.assertRestrictions(
1853 DpmTestUtils.newRestrictions(defaultRestrictions),
1854 dpm.getUserRestrictions(admin1)
1855 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001856 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001857 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001858 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001859 eq(true) /* isDeviceOwner */,
1860 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001861 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001862 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001863
1864 for (String restriction : defaultRestrictions) {
1865 dpm.clearUserRestriction(admin1, restriction);
1866 }
1867
1868 assertNoDeviceOwnerRestrictions();
1869
1870 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001871 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001872 initializeDpms();
1873 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1874 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1875
1876 assertNoDeviceOwnerRestrictions();
1877
1878 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1879 // is set as it wasn't enabled during setDeviceOwner.
1880 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1881 assertFalse(UserRestrictionsUtils
1882 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1883 UserRestrictionsUtils
1884 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1885 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001886 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001887 initializeDpms();
1888 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1889 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1890
1891 DpmTestUtils.assertRestrictions(
1892 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1893 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1894 );
1895 DpmTestUtils.assertRestrictions(
1896 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1897 dpm.getUserRestrictions(admin1)
1898 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001899 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001900 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001901 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001902 eq(true) /* isDeviceOwner */,
1903 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001904 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001905 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001906
1907 // Remove the restriction.
1908 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1909
1910 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1911 initializeDpms();
1912 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1913 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1914 assertNoDeviceOwnerRestrictions();
1915 } finally {
1916 UserRestrictionsUtils
1917 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1918 }
1919 }
1920
1921 private void assertNoDeviceOwnerRestrictions() {
1922 DpmTestUtils.assertRestrictions(
1923 DpmTestUtils.newRestrictions(),
1924 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1925 );
1926 DpmTestUtils.assertRestrictions(
1927 DpmTestUtils.newRestrictions(),
1928 dpm.getUserRestrictions(admin1)
1929 );
1930 }
1931
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001932 public void testGetMacAddress() throws Exception {
1933 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1934 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1935 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1936
1937 // In this test, change the caller user to "system".
1938 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1939
1940 // Make sure admin1 is installed on system user.
1941 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1942
1943 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001944 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1945 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001946
1947 // DO needs to be an DA.
1948 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1949 assertTrue(dpm.isAdminActive(admin1));
1950
1951 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001952 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1953 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001954
1955 // Test 3. Caller has PO, but not DO.
1956 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001957 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1958 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001959
1960 // Remove PO.
1961 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001962 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001963 // Test 4, Caller is DO now.
1964 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1965
1966 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001967 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001968
1969 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001970 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001971 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001972
1973 // 4-3. With a real MAC address.
1974 final WifiInfo wi = new WifiInfo();
1975 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001976 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001977 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001978 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001979
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001980 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001981 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1982 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1983
1984 // In this test, change the caller user to "system".
1985 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1986
1987 // Make sure admin1 is installed on system user.
1988 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1989
1990 // Set admin1 as DA.
1991 dpm.setActiveAdmin(admin1, false);
1992 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001993 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1994 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001995
1996 // Set admin1 as PO.
1997 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001998 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1999 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002000
2001 // Remove PO and add DO.
2002 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002003 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002004 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2005
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002006 // admin1 is DO.
2007 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002008 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002009 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002010 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2011 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002012
2013 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002014 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002015 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002016 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2017 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002018
2019 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002020 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002021 dpm.reboot(admin1);
2022 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002023
2024 public void testSetGetSupportText() {
2025 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2026 dpm.setActiveAdmin(admin1, true);
2027 dpm.setActiveAdmin(admin2, true);
2028 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2029
2030 // Null default support messages.
2031 {
2032 assertNull(dpm.getLongSupportMessage(admin1));
2033 assertNull(dpm.getShortSupportMessage(admin1));
2034 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2035 assertNull(dpm.getShortSupportMessageForUser(admin1,
2036 DpmMockContext.CALLER_USER_HANDLE));
2037 assertNull(dpm.getLongSupportMessageForUser(admin1,
2038 DpmMockContext.CALLER_USER_HANDLE));
2039 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2040 }
2041
2042 // Only system can call the per user versions.
2043 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002044 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2045 () -> dpm.getShortSupportMessageForUser(admin1,
2046 DpmMockContext.CALLER_USER_HANDLE));
2047 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2048 () -> dpm.getLongSupportMessageForUser(admin1,
2049 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002050 }
2051
2052 // Can't set message for admin in another uid.
2053 {
2054 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002055 assertExpectException(SecurityException.class,
2056 /* messageRegex= */ "is not owned by uid",
2057 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002058 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2059 }
2060
2061 // Set/Get short returns what it sets and other admins text isn't changed.
2062 {
2063 final String supportText = "Some text to test with.";
2064 dpm.setShortSupportMessage(admin1, supportText);
2065 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2066 assertNull(dpm.getLongSupportMessage(admin1));
2067 assertNull(dpm.getShortSupportMessage(admin2));
2068
2069 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2070 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2071 DpmMockContext.CALLER_USER_HANDLE));
2072 assertNull(dpm.getShortSupportMessageForUser(admin2,
2073 DpmMockContext.CALLER_USER_HANDLE));
2074 assertNull(dpm.getLongSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2077
2078 dpm.setShortSupportMessage(admin1, null);
2079 assertNull(dpm.getShortSupportMessage(admin1));
2080 }
2081
2082 // Set/Get long returns what it sets and other admins text isn't changed.
2083 {
2084 final String supportText = "Some text to test with.\nWith more text.";
2085 dpm.setLongSupportMessage(admin1, supportText);
2086 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2087 assertNull(dpm.getShortSupportMessage(admin1));
2088 assertNull(dpm.getLongSupportMessage(admin2));
2089
2090 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2091 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2092 DpmMockContext.CALLER_USER_HANDLE));
2093 assertNull(dpm.getLongSupportMessageForUser(admin2,
2094 DpmMockContext.CALLER_USER_HANDLE));
2095 assertNull(dpm.getShortSupportMessageForUser(admin1,
2096 DpmMockContext.CALLER_USER_HANDLE));
2097 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2098
2099 dpm.setLongSupportMessage(admin1, null);
2100 assertNull(dpm.getLongSupportMessage(admin1));
2101 }
2102 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002103
phweiss73145f42017-01-17 19:06:38 +01002104 public void testCreateAdminSupportIntent() throws Exception {
2105 // Setup device owner.
2106 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2107 setupDeviceOwner();
2108
2109 // Nonexisting permission returns null
2110 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2111 assertNull(intent);
2112
2113 // Existing permission that is not set returns null
2114 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2115 assertNull(intent);
2116
2117 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002118 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002119 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2120 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2121 .thenReturn(true);
2122 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2123 assertNull(intent);
2124
2125 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002126 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002127 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2128 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2129 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2130 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2131 assertNotNull(intent);
2132 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2133 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2134 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002135 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002136 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2137 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2138
2139 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2140 // user restrictions
2141
2142 // Camera is not disabled
2143 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2144 assertNull(intent);
2145
2146 // Camera is disabled
2147 dpm.setCameraDisabled(admin1, true);
2148 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2149 assertNotNull(intent);
2150 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2151 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2152
2153 // Screen capture is not disabled
2154 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2155 assertNull(intent);
2156
2157 // Screen capture is disabled
2158 dpm.setScreenCaptureDisabled(admin1, true);
2159 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2160 assertNotNull(intent);
2161 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2162 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2163
2164 // Same checks for different user
2165 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2166 // Camera should be disabled by device owner
2167 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2168 assertNotNull(intent);
2169 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2170 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2171 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2172 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2173 // ScreenCapture should not be disabled by device owner
2174 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2175 assertNull(intent);
2176 }
2177
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002178 /**
2179 * Test for:
2180 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002181 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002182 * {@link DevicePolicyManager#isAffiliatedUser}
2183 */
2184 public void testUserAffiliation() throws Exception {
2185 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2186 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2187 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2188
2189 // Check that the system user is unaffiliated.
2190 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2191 assertFalse(dpm.isAffiliatedUser());
2192
2193 // Set a device owner on the system user. Check that the system user becomes affiliated.
2194 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2195 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2196 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2197 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002198 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002199
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002200 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002201 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2202 setAsProfileOwner(admin2);
2203 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002204 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002205
2206 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2207 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002208 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002209 userAffiliationIds.add("red");
2210 userAffiliationIds.add("green");
2211 userAffiliationIds.add("blue");
2212 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002213 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002214 assertFalse(dpm.isAffiliatedUser());
2215
2216 // Have the device owner specify a set of affiliation ids that do not intersect with those
2217 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002218 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002219 deviceAffiliationIds.add("cyan");
2220 deviceAffiliationIds.add("yellow");
2221 deviceAffiliationIds.add("magenta");
2222 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2223 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002224 MoreAsserts.assertContentsInAnyOrder(
2225 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002226 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2227 assertFalse(dpm.isAffiliatedUser());
2228
2229 // Have the profile owner specify a set of affiliation ids that intersect with those
2230 // specified by the device owner. Check that the test user becomes affiliated.
2231 userAffiliationIds.add("yellow");
2232 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002233 MoreAsserts.assertContentsInAnyOrder(
2234 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002235 assertTrue(dpm.isAffiliatedUser());
2236
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002237 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002238 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002239 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002240 assertFalse(dpm.isAffiliatedUser());
2241
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002242 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2243 dpm.setAffiliationIds(admin2, userAffiliationIds);
2244 assertTrue(dpm.isAffiliatedUser());
2245 dpm.clearProfileOwner(admin2);
2246 assertFalse(dpm.isAffiliatedUser());
2247
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002248 // Check that the system user remains affiliated.
2249 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2250 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002251
2252 // Clear the device owner - the user becomes unaffiliated.
2253 clearDeviceOwner();
2254 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002255 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002256
2257 public void testGetUserProvisioningState_defaultResult() {
2258 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2259 }
2260
2261 public void testSetUserProvisioningState_permission() throws Exception {
2262 setupProfileOwner();
2263 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2264
2265 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2266 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2267 }
2268
2269 public void testSetUserProvisioningState_unprivileged() throws Exception {
2270 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002271 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2272 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2273 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002274 }
2275
2276 public void testSetUserProvisioningState_noManagement() {
2277 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002278 assertExpectException(IllegalStateException.class,
2279 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2280 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2281 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002282 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2283 }
2284
2285 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2287 setupDeviceOwner();
2288 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2289
2290 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2291 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2292 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2293 }
2294
2295 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2296 throws Exception {
2297 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2298 setupDeviceOwner();
2299 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2300
2301 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2302 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2303 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2304 }
2305
2306 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2307 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2308 setupDeviceOwner();
2309 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2310
2311 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2312 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2313 }
2314
2315 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2316 throws Exception {
2317 setupProfileOwner();
2318 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2319
2320 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2321 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2322 DevicePolicyManager.STATE_USER_UNMANAGED);
2323 }
2324
2325 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2326 throws Exception {
2327 setupProfileOwner();
2328 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2329
2330 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2331 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2332 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2333 }
2334
2335 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2336 setupProfileOwner();
2337 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2338
2339 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2340 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2341 }
2342
2343 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2344 setupProfileOwner();
2345 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2346
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002347 assertExpectException(IllegalStateException.class,
2348 /* messageRegex= */ "Cannot move to user provisioning state",
2349 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2350 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2351 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002352 }
2353
2354 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2355 throws Exception {
2356 setupProfileOwner();
2357 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2358
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002359 assertExpectException(IllegalStateException.class,
2360 /* messageRegex= */ "Cannot move to user provisioning state",
2361 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2362 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2363 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002364 }
2365
2366 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2367 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2368 for (int state : states) {
2369 dpm.setUserProvisioningState(state, userId);
2370 assertEquals(state, dpm.getUserProvisioningState());
2371 }
2372 }
2373
2374 private void setupProfileOwner() throws Exception {
2375 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2376
2377 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2378 dpm.setActiveAdmin(admin1, false);
2379 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2380
2381 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2382 }
2383
2384 private void setupDeviceOwner() throws Exception {
2385 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2386
2387 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2388 dpm.setActiveAdmin(admin1, false);
2389 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2390
2391 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2392 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002393
2394 public void testSetMaximumTimeToLock() {
2395 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2396
2397 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2398 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2399
Pavel Grafov75c0a892017-05-18 17:28:27 +01002400 reset(getServices().powerManagerInternal);
2401 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002402
2403 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002404 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2405 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002406 reset(getServices().powerManagerInternal);
2407 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002408
2409 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002410 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2411 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002412 reset(getServices().powerManagerInternal);
2413 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002414
2415 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002416 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2417 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002418 reset(getServices().powerManagerInternal);
2419 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002420
2421 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002422 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2423 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002424 reset(getServices().powerManagerInternal);
2425 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002426
2427 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002428 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2429 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002430 reset(getServices().powerManagerInternal);
2431 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002432
2433 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002434 reset(getServices().powerManagerInternal);
2435 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002436
Pavel Grafov28939982017-10-03 15:11:52 +01002437 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2438 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2439 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002440 reset(getServices().powerManagerInternal);
2441 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002442
2443 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002444 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2445 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002446 reset(getServices().powerManagerInternal);
2447 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002448
Pavel Grafov28939982017-10-03 15:11:52 +01002449 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002450 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002451 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2452 verifyStayOnWhilePluggedCleared(false);
2453 }
2454
2455 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2456 // uses separate challenge.
2457 public void testSetMaximumTimeToLockProfile() throws Exception {
2458 final int PROFILE_USER = 15;
2459 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2460 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2461 mContext.binder.callingUid = PROFILE_ADMIN;
2462 final DevicePolicyManagerInternal dpmi =
2463 LocalServices.getService(DevicePolicyManagerInternal.class);
2464
2465 dpm.setMaximumTimeToLock(admin1, 0);
2466
2467 reset(getServices().powerManagerInternal);
2468 reset(getServices().settings);
2469
2470 // First add timeout for the profile.
2471 dpm.setMaximumTimeToLock(admin1, 10);
2472 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2473
2474 reset(getServices().powerManagerInternal);
2475 reset(getServices().settings);
2476
2477 // Add separate challenge
2478 when(getServices().lockPatternUtils
2479 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2480 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2481
2482 verifyScreenTimeoutCall(10L, PROFILE_USER);
2483 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2484
2485 reset(getServices().powerManagerInternal);
2486 reset(getServices().settings);
2487
2488 // Remove the timeout.
2489 dpm.setMaximumTimeToLock(admin1, 0);
2490 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2491 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2492
2493 reset(getServices().powerManagerInternal);
2494 reset(getServices().settings);
2495
2496 // Add it back.
2497 dpm.setMaximumTimeToLock(admin1, 10);
2498 verifyScreenTimeoutCall(10L, PROFILE_USER);
2499 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2500
2501 reset(getServices().powerManagerInternal);
2502 reset(getServices().settings);
2503
2504 // Remove separate challenge.
2505 reset(getServices().lockPatternUtils);
2506 when(getServices().lockPatternUtils
2507 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2508 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2509
2510 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2511 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2512
2513 reset(getServices().powerManagerInternal);
2514 reset(getServices().settings);
2515
2516 // Remove the timeout.
2517 dpm.setMaximumTimeToLock(admin1, 0);
2518 verifyScreenTimeoutCall(null, PROFILE_USER);
2519 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002520 }
2521
Michal Karpinski943aabd2016-10-06 11:09:25 +01002522 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2523 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2524 setupDeviceOwner();
2525 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2526
Michal Karpinskid084ca52017-01-18 15:54:18 +00002527 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2528 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2529 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2530 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2531 - ONE_MINUTE;
2532
2533 // verify that the minimum timeout cannot be modified on user builds (system property is
2534 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002535 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002536
2537 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2538 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2539 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2540
Pavel Grafov75c0a892017-05-18 17:28:27 +01002541 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002542
2543 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002544 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002545
Michal Karpinskid084ca52017-01-18 15:54:18 +00002546 // reset to default (0 means the admin is not participating, so default should be returned)
2547 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002548
2549 // aggregation should be the default if unset by any admin
2550 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2551 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2552
2553 // admin not participating by default
2554 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2555
2556 //clamping from the top
2557 dpm.setRequiredStrongAuthTimeout(admin1,
2558 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2559 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2560 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2561 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2562 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2563
Michal Karpinskid084ca52017-01-18 15:54:18 +00002564 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002565 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2566 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2567 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2568 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2569
2570 // clamping from the bottom
2571 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2572 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2573 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2574
Michal Karpinskid084ca52017-01-18 15:54:18 +00002575 // values within range
2576 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2577 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2578 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2579
2580 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2581 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2582 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002583
2584 // reset to default
2585 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2586 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2587 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2588 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2589
2590 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002591 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2592 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002593 }
2594
Pavel Grafov28939982017-10-03 15:11:52 +01002595 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002596 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002597 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002598 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002599 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002600 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002601 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002602 }
Pavel Grafov28939982017-10-03 15:11:52 +01002603 }
2604
2605 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002606 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2607 // UnfinishedVerificationException.
2608 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002609
Esteban Talavera01576862016-12-15 11:16:44 +00002610 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002611 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002612 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002613 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002614 .thenReturn(false);
2615 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002616 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2617 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002618 .thenReturn(true);
2619 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2620
2621 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002622 }
Victor Chang3e794af2016-03-04 13:48:17 +00002623
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002624 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2625 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002626 mContext.packageName = admin1.getPackageName();
2627 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002628 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2629 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2630 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2631 false);
2632 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2633 }
2634
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002635 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2636 setup_DeviceAdminFeatureOff();
2637 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2638 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2639 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2640 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2641 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2642 assertCheckProvisioningPreCondition(
2643 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2644 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2645 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2646 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2647 }
2648
Esteban Talavera01576862016-12-15 11:16:44 +00002649 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002650 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002651 .thenReturn(false);
2652 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002653 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2654 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002655 .thenReturn(true);
2656 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2657
2658 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002659 }
Victor Chang3e794af2016-03-04 13:48:17 +00002660
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002661 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2662 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002663 mContext.packageName = admin1.getPackageName();
2664 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002665 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2666 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2667 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2668 false);
2669 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2670
2671 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002672 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002673 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2674 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2675 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2676 true);
2677 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2678 }
2679
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002680 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2681 setup_ManagedProfileFeatureOff();
2682 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2683 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2684 DevicePolicyManager.CODE_OK);
2685 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2686 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2687 assertCheckProvisioningPreCondition(
2688 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2689 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2690 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2691 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2692
2693 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002694 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002695 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2696 DevicePolicyManager.CODE_OK);
2697 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2698 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2699 assertCheckProvisioningPreCondition(
2700 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2701 DevicePolicyManager.CODE_OK);
2702 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2703 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2704 }
2705
Esteban Talavera01576862016-12-15 11:16:44 +00002706 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002707 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002708 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002709 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2710 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002711 .thenReturn(true);
2712 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2713
2714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002715 }
Victor Chang3e794af2016-03-04 13:48:17 +00002716
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002717 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2718 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002719 mContext.packageName = admin1.getPackageName();
2720 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002721 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2722 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2723 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2724 false /* because of non-split user */);
2725 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2726 false /* because of non-split user */);
2727 }
2728
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002729 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002730 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002731 setup_nonSplitUser_firstBoot_primaryUser();
2732 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2733 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2734 DevicePolicyManager.CODE_OK);
2735 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2736 DevicePolicyManager.CODE_OK);
2737 assertCheckProvisioningPreCondition(
2738 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2739 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2740 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2741 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2742 }
2743
Esteban Talavera01576862016-12-15 11:16:44 +00002744 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002745 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002746 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002747 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2748 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002749 .thenReturn(true);
2750 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2751
2752 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002753 }
Victor Chang3e794af2016-03-04 13:48:17 +00002754
Nicolas Prevot45d29072017-01-18 16:11:19 +00002755 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2756 setDeviceOwner();
2757 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2758 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2759 }
2760
2761 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2762 setup_nonSplitUser_withDo_primaryUser();
2763 final int MANAGED_PROFILE_USER_ID = 18;
2764 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2765 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002767 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002768 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002769 true)).thenReturn(true);
2770 }
2771
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002772 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2773 throws Exception {
2774 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002775 mContext.packageName = admin1.getPackageName();
2776 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2778 false/* because of completed device setup */);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2780 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2781 false/* because of non-split user */);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2783 false/* because of non-split user */);
2784 }
2785
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002786 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2787 throws Exception {
2788 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2789 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2790 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2791 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2792 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2793 DevicePolicyManager.CODE_OK);
2794 assertCheckProvisioningPreCondition(
2795 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2796 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2798 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2799 }
2800
Nicolas Prevot45d29072017-01-18 16:11:19 +00002801 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2802 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002803 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002804 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2805
2806 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2807 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002808 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002809
2810 // COMP mode is allowed.
2811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2812 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002813 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002814
Nicolas Prevot45d29072017-01-18 16:11:19 +00002815 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002816 assertCheckProvisioningPreCondition(
2817 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002818 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002819 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002820 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2821 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2822 }
Esteban Talavera01576862016-12-15 11:16:44 +00002823
Nicolas Prevot45d29072017-01-18 16:11:19 +00002824 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2825 setup_nonSplitUser_withDo_primaryUser();
2826 mContext.packageName = admin1.getPackageName();
2827 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2828 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2829 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002830 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002831 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2832 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2833 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002834 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002835 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2836 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2837 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2838 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2839 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002841 assertCheckProvisioningPreCondition(
2842 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002843 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002844 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002845 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2846 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2847 }
Esteban Talavera01576862016-12-15 11:16:44 +00002848
Nicolas Prevot45d29072017-01-18 16:11:19 +00002849 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2850 throws Exception {
2851 setup_nonSplitUser_withDo_primaryUser();
2852 mContext.packageName = admin1.getPackageName();
2853 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002854 // The DO should not be allowed to initiate provisioning if the restriction is set by
2855 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002856 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002857 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2858 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2859 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002860 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002861 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2862 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2863 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2864 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2865 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2867
2868 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002869 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002870 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002871 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002872 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2873 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2874 }
2875
2876 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2877 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2878 mContext.packageName = admin1.getPackageName();
2879 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2880
2881 // We can delete the managed profile to create a new one, so provisioning is allowed.
2882 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2883 DevicePolicyManager.CODE_OK);
2884 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2885 assertCheckProvisioningPreCondition(
2886 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2887 DpmMockContext.ANOTHER_PACKAGE_NAME,
2888 DevicePolicyManager.CODE_OK);
2889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2890 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2891 }
2892
2893 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2894 throws Exception {
2895 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2896 mContext.packageName = admin1.getPackageName();
2897 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002898 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002899 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2900 eq(UserHandle.SYSTEM)))
2901 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002902 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002903 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2904 eq(UserHandle.SYSTEM)))
2905 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002906
2907 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002908 assertCheckProvisioningPreCondition(
2909 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2910 DpmMockContext.ANOTHER_PACKAGE_NAME,
2911 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2912 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2913 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002914
2915 // But the device owner can still do it because it has set the restriction itself.
2916 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2917 DevicePolicyManager.CODE_OK);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002919 }
2920
2921 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002922 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002923 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002924 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2925 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002926 .thenReturn(false);
2927 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2928
2929 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002930 }
Victor Chang3e794af2016-03-04 13:48:17 +00002931
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002932 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2933 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002934 mContext.packageName = admin1.getPackageName();
2935 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2938 false /* because canAddMoreManagedProfiles returns false */);
2939 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2940 true);
2941 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2942 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002943 }
2944
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002945 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2946 throws Exception {
2947 setup_splitUser_firstBoot_systemUser();
2948 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2949 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2950 DevicePolicyManager.CODE_OK);
2951 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002952 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002953 assertCheckProvisioningPreCondition(
2954 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2955 DevicePolicyManager.CODE_OK);
2956 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2957 DevicePolicyManager.CODE_SYSTEM_USER);
2958 }
2959
Esteban Talavera01576862016-12-15 11:16:44 +00002960 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002961 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002962 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002963 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2964 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002965 .thenReturn(false);
2966 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2967
2968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002969 }
Victor Chang3e794af2016-03-04 13:48:17 +00002970
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002971 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2972 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002973 mContext.packageName = admin1.getPackageName();
2974 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002975 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2976 true/* it's undefined behavior. Can be changed into false in the future */);
2977 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2978 false /* because canAddMoreManagedProfiles returns false */);
2979 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2980 true/* it's undefined behavior. Can be changed into false in the future */);
2981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2982 false/* because calling uid is system user */);
2983 }
2984
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002985 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2986 throws Exception {
2987 setup_splitUser_afterDeviceSetup_systemUser();
2988 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2989 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2990 DevicePolicyManager.CODE_OK);
2991 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002992 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 assertCheckProvisioningPreCondition(
2994 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2995 DevicePolicyManager.CODE_OK);
2996 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2997 DevicePolicyManager.CODE_SYSTEM_USER);
2998 }
2999
Esteban Talavera01576862016-12-15 11:16:44 +00003000 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003001 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003002 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003003 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3004 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003005 true)).thenReturn(true);
3006 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3007
3008 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003009 }
Victor Chang3e794af2016-03-04 13:48:17 +00003010
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003011 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3012 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003013 mContext.packageName = admin1.getPackageName();
3014 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003015 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3016 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3017 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3018 true);
3019 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003020 }
3021
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003022 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003023 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003024 setup_splitUser_firstBoot_primaryUser();
3025 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3026 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3027 DevicePolicyManager.CODE_OK);
3028 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3029 DevicePolicyManager.CODE_OK);
3030 assertCheckProvisioningPreCondition(
3031 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3032 DevicePolicyManager.CODE_OK);
3033 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3034 DevicePolicyManager.CODE_OK);
3035 }
3036
Esteban Talavera01576862016-12-15 11:16:44 +00003037 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003039 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003040 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3041 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003042 true)).thenReturn(true);
3043 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3044
3045 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003046 }
Victor Chang3e794af2016-03-04 13:48:17 +00003047
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003048 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3049 throws Exception {
3050 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003051 mContext.packageName = admin1.getPackageName();
3052 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3054 true/* it's undefined behavior. Can be changed into false in the future */);
3055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3057 true/* it's undefined behavior. Can be changed into false in the future */);
3058 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3059 false/* because user setup completed */);
3060 }
3061
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003062 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003063 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003064 setup_splitUser_afterDeviceSetup_primaryUser();
3065 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3066 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3067 DevicePolicyManager.CODE_OK);
3068 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3069 DevicePolicyManager.CODE_OK);
3070 assertCheckProvisioningPreCondition(
3071 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3072 DevicePolicyManager.CODE_OK);
3073 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3074 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3075 }
3076
Esteban Talavera01576862016-12-15 11:16:44 +00003077 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003078 setDeviceOwner();
3079
Pavel Grafov75c0a892017-05-18 17:28:27 +01003080 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003081 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003082 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3083 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003084 .thenReturn(false);
3085 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3086
3087 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003088 }
Victor Chang3e794af2016-03-04 13:48:17 +00003089
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003090 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3091 throws Exception {
3092 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003093 mContext.packageName = admin1.getPackageName();
3094 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3096 false /* can't provision managed profile on system user */);
3097 }
3098
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003099 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003100 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3102 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3103 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3104 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3105 }
3106
3107 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003108 setDeviceOwner();
3109
Pavel Grafov75c0a892017-05-18 17:28:27 +01003110 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003111 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003112 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3113 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003114 true)).thenReturn(true);
3115 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3116
3117 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003118 }
Victor Chang3e794af2016-03-04 13:48:17 +00003119
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003120 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3121 throws Exception {
3122 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003123 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3124 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003125 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3126 }
3127
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003128 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003129 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003130 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3131 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003132
3133 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003134 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3135 DevicePolicyManager.CODE_OK);
3136 }
3137
3138 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003139 setDeviceOwner();
3140
Pavel Grafov75c0a892017-05-18 17:28:27 +01003141 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003142 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003143 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3144 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003145 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3146 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003147 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003148 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003149 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003150 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003151 true)).thenReturn(true);
3152 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3153
3154 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003155 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003156
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003157 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3158 throws Exception {
3159 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003160 mContext.packageName = admin1.getPackageName();
3161 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003162 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3163 }
3164
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003165 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3166 throws Exception {
3167 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3168 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3169 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3170 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3171 }
3172
3173 public void testCheckProvisioningPreCondition_permission() {
3174 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003175 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3176 () -> dpm.checkProvisioningPreCondition(
3177 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003178 }
3179
Victor Chang3577ed22016-08-25 18:49:26 +01003180 public void testForceUpdateUserSetupComplete_permission() {
3181 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003182 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3183 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003184 }
3185
3186 public void testForceUpdateUserSetupComplete_systemUser() {
3187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3188 // GIVEN calling from user 20
3189 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003190 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3191 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003192 }
3193
3194 public void testForceUpdateUserSetupComplete_userbuild() {
3195 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3196 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3197
3198 final int userId = UserHandle.USER_SYSTEM;
3199 // GIVEN userComplete is false in SettingsProvider
3200 setUserSetupCompleteForUser(false, userId);
3201
3202 // GIVEN userComplete is true in DPM
3203 DevicePolicyManagerService.DevicePolicyData userData =
3204 new DevicePolicyManagerService.DevicePolicyData(userId);
3205 userData.mUserSetupComplete = true;
3206 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3207
3208 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003209 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003210
3211 assertTrue(dpms.hasUserSetupCompleted());
3212
3213 dpm.forceUpdateUserSetupComplete();
3214
3215 // THEN the state in dpms is not changed
3216 assertTrue(dpms.hasUserSetupCompleted());
3217 }
3218
3219 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3220 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3221 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3222
3223 final int userId = UserHandle.USER_SYSTEM;
3224 // GIVEN userComplete is false in SettingsProvider
3225 setUserSetupCompleteForUser(false, userId);
3226
3227 // GIVEN userComplete is true in DPM
3228 DevicePolicyManagerService.DevicePolicyData userData =
3229 new DevicePolicyManagerService.DevicePolicyData(userId);
3230 userData.mUserSetupComplete = true;
3231 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3232
3233 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003234 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003235
3236 assertTrue(dpms.hasUserSetupCompleted());
3237
3238 dpm.forceUpdateUserSetupComplete();
3239
3240 // THEN the state in dpms is not changed
3241 assertFalse(dpms.hasUserSetupCompleted());
3242 }
3243
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003244 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003245 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003246 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003247
3248 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3249 runAsCaller(mAdmin1Context, dpms, dpm -> {
3250 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3251 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003252 }
3253
3254 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3255 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3256 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003257
3258 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3259 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003260 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003261 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3262 .thenReturn(true);
3263
3264 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003265 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003266
3267 // Enabling logging should not change the timestamp.
3268 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003269 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003270 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003271 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003272 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003273 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003274
3275 // Retrieving the logs should update the timestamp.
3276 final long beforeRetrieval = System.currentTimeMillis();
3277 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003278 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003279 final long afterRetrieval = System.currentTimeMillis();
3280 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3281 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3282
3283 // Retrieving the pre-boot logs should update the timestamp.
3284 Thread.sleep(2);
3285 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003286 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003287 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3288
3289 // Checking the timestamp again should not change it.
3290 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003291 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003292
3293 // Retrieving the logs again should update the timestamp.
3294 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003295 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003296 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3297
3298 // Disabling logging should not change the timestamp.
3299 Thread.sleep(2);
3300 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003301 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003302
3303 // Restarting the DPMS should not lose the timestamp.
3304 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003305 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003306
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003307 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3308 mContext.binder.callingUid = 1234567;
3309 mContext.callerPermissions.add(permission.MANAGE_USERS);
3310 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3311 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3312
3313 // System can retrieve the timestamp.
3314 mContext.binder.clearCallingIdentity();
3315 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3316
3317 // Removing the device owner should clear the timestamp.
3318 clearDeviceOwner();
3319 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003320 }
3321
yuemingw0de748d2017-11-15 19:22:27 +00003322 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3323 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3324 setupDeviceOwner();
3325 assertExpectException(SecurityException.class, null, () ->
3326 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3327 }
3328
3329 public void testSetSystemSettingFailWithPO() throws Exception {
3330 setupProfileOwner();
3331 assertExpectException(SecurityException.class, null, () ->
3332 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3333 }
3334
3335 public void testSetSystemSetting() throws Exception {
3336 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3337 setupDeviceOwner();
3338 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3339 verify(getServices().settings).settingsSystemPutString(
3340 Settings.System.SCREEN_BRIGHTNESS, "0");
3341 }
3342
yuemingwe43cdf72017-10-12 16:52:11 +01003343 public void testSetTime() throws Exception {
3344 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3345 setupDeviceOwner();
3346 dpm.setTime(admin1, 0);
3347 verify(getServices().alarmManager).setTime(0);
3348 }
3349
3350 public void testSetTimeFailWithPO() throws Exception {
3351 setupProfileOwner();
3352 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3353 }
3354
3355 public void testSetTimeWithAutoTimeOn() throws Exception {
3356 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3357 setupDeviceOwner();
3358 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3359 .thenReturn(1);
3360 assertFalse(dpm.setTime(admin1, 0));
3361 }
3362
3363 public void testSetTimeZone() throws Exception {
3364 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3365 setupDeviceOwner();
3366 dpm.setTimeZone(admin1, "Asia/Shanghai");
3367 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3368 }
3369
3370 public void testSetTimeZoneFailWithPO() throws Exception {
3371 setupProfileOwner();
3372 assertExpectException(SecurityException.class, null,
3373 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3374 }
3375
3376 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3377 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3378 setupDeviceOwner();
3379 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3380 .thenReturn(1);
3381 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3382 }
3383
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003384 public void testGetLastBugReportRequestTime() throws Exception {
3385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3386 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003387
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003388 mContext.packageName = admin1.getPackageName();
3389 mContext.applicationInfo = new ApplicationInfo();
3390 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3391 .thenReturn(Color.WHITE);
3392 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3393 anyObject())).thenReturn(Color.WHITE);
3394
Esteban Talaverad36dd152016-12-15 08:51:45 +00003395 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3396 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003397 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003398
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003399 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003400 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003401
3402 // Requesting a bug report should update the timestamp.
3403 final long beforeRequest = System.currentTimeMillis();
3404 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003405 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003406 final long afterRequest = System.currentTimeMillis();
3407 assertTrue(bugReportRequestTime >= beforeRequest);
3408 assertTrue(bugReportRequestTime <= afterRequest);
3409
3410 // Checking the timestamp again should not change it.
3411 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003412 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003413
3414 // Restarting the DPMS should not lose the timestamp.
3415 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003416 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003417
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003418 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3419 mContext.binder.callingUid = 1234567;
3420 mContext.callerPermissions.add(permission.MANAGE_USERS);
3421 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3422 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3423
3424 // System can retrieve the timestamp.
3425 mContext.binder.clearCallingIdentity();
3426 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3427
3428 // Removing the device owner should clear the timestamp.
3429 clearDeviceOwner();
3430 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003431 }
3432
3433 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3434 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3435 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003436 mContext.packageName = admin1.getPackageName();
3437 mContext.applicationInfo = new ApplicationInfo();
3438 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3439 .thenReturn(Color.WHITE);
3440 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3441 anyObject())).thenReturn(Color.WHITE);
3442
3443 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3444 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003445 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003446 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003447 .thenReturn(true);
3448
3449 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003450 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003451
3452 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3453 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003454 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003455
3456 // Enabling logging should not change the timestamp.
3457 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003458 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003459
3460 // Retrieving the logs should update the timestamp.
3461 final long beforeRetrieval = System.currentTimeMillis();
3462 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003463 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003464 final long afterRetrieval = System.currentTimeMillis();
3465 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3466 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3467
3468 // Checking the timestamp again should not change it.
3469 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003470 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003471
3472 // Retrieving the logs again should update the timestamp.
3473 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003474 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003475 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3476
3477 // Disabling logging should not change the timestamp.
3478 Thread.sleep(2);
3479 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003480 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003481
3482 // Restarting the DPMS should not lose the timestamp.
3483 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003484 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3485
3486 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3487 mContext.binder.callingUid = 1234567;
3488 mContext.callerPermissions.add(permission.MANAGE_USERS);
3489 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3490 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3491
3492 // System can retrieve the timestamp.
3493 mContext.binder.clearCallingIdentity();
3494 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3495
3496 // Removing the device owner should clear the timestamp.
3497 clearDeviceOwner();
3498 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003499 }
3500
Tony Mak2f26b792016-11-28 17:54:51 +00003501 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3502 // Setup device owner.
3503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3504 setupDeviceOwner();
3505
3506 // Only device owner is setup, the result list should be empty.
3507 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3508 MoreAsserts.assertEmpty(targetUsers);
3509
3510 // Setup a managed profile managed by the same admin.
3511 final int MANAGED_PROFILE_USER_ID = 15;
3512 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3513 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3514
3515 // Add a secondary user, it should never talk with.
3516 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003517 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003518
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003519 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3520 // other.
3521 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3522 MoreAsserts.assertEmpty(targetUsers);
3523
3524 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3525 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3526 MoreAsserts.assertEmpty(targetUsers);
3527
3528 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003529 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003530 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3531 dpm.setAffiliationIds(admin1, userAffiliationIds);
3532
3533 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3534 dpm.setAffiliationIds(admin1, userAffiliationIds);
3535
Tony Mak2f26b792016-11-28 17:54:51 +00003536 // Calling from device owner admin, the result list should just contain the managed
3537 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003539 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3540 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3541
3542 // Calling from managed profile admin, the result list should just contain the system
3543 // user id.
3544 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3545 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3546 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003547
3548 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003549 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003550
3551 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3552 // to each other.
3553 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3554 MoreAsserts.assertEmpty(targetUsers);
3555
3556 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3557 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3558 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003559 }
3560
3561 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3562 // Setup a device owner.
3563 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3564 setupDeviceOwner();
3565
3566 // Set up a managed profile managed by different package.
3567 final int MANAGED_PROFILE_USER_ID = 15;
3568 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3569 final ComponentName adminDifferentPackage =
3570 new ComponentName("another.package", "whatever.class");
3571 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3572
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003573 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003574 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003575 dpm.setAffiliationIds(admin1, userAffiliationIds);
3576
3577 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3578 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3579
Tony Mak2f26b792016-11-28 17:54:51 +00003580 // Calling from device owner admin, we should get zero bind device admin target users as
3581 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003582 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003583 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3584 MoreAsserts.assertEmpty(targetUsers);
3585
3586 // Calling from managed profile admin, we should still get zero target users for the same
3587 // reason.
3588 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3589 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3590 MoreAsserts.assertEmpty(targetUsers);
3591 }
3592
Charles Hee078db72017-10-19 18:03:20 +01003593 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003594 // Setup a device owner.
3595 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3596 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003597 // Lock task policy is updated when loading user data.
3598 verify(getServices().iactivityManager).updateLockTaskPackages(
3599 UserHandle.USER_SYSTEM, new String[0]);
3600 verify(getServices().iactivityManager).updateLockTaskFeatures(
3601 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003602
3603 // Set up a managed profile managed by different package (package name shouldn't matter)
3604 final int MANAGED_PROFILE_USER_ID = 15;
3605 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3606 final ComponentName adminDifferentPackage =
3607 new ComponentName("another.package", "whatever.class");
3608 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003609 verify(getServices().iactivityManager).updateLockTaskPackages(
3610 MANAGED_PROFILE_USER_ID, new String[0]);
3611 verify(getServices().iactivityManager).updateLockTaskFeatures(
3612 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003613
3614 // The DO can still set lock task packages
3615 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3616 final String[] doPackages = {"doPackage1", "doPackage2"};
3617 dpm.setLockTaskPackages(admin1, doPackages);
3618 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3619 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3620 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003621 verify(getServices().iactivityManager).updateLockTaskPackages(
3622 UserHandle.USER_SYSTEM, doPackages);
3623 // And the DO can still set lock task features
3624 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3625 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3626 dpm.setLockTaskFeatures(admin1, doFlags);
3627 verify(getServices().iactivityManager).updateLockTaskFeatures(
3628 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003629
3630 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3631 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3632 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003633 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3634 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3635 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3636 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003637 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003638 // And it shouldn't be able to setLockTaskFeatures.
3639 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3640 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3641 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3642 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003643
3644 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003645 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003646 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3647 dpm.setAffiliationIds(admin1, userAffiliationIds);
3648
3649 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3650 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3651
3652 // Now the managed profile can set lock task packages.
3653 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3654 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3655 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3656 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003657 verify(getServices().iactivityManager).updateLockTaskPackages(
3658 MANAGED_PROFILE_USER_ID, poPackages);
3659 // And it can set lock task features.
3660 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3661 verify(getServices().iactivityManager).updateLockTaskFeatures(
3662 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003663
3664 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003665 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003666 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3667 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003668 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3669 MANAGED_PROFILE_USER_ID, new String[0]);
3670 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3671 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003672
3673 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3674 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3675 }
3676
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003677 public void testIsDeviceManaged() throws Exception {
3678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3679 setupDeviceOwner();
3680
3681 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3682 // find out that the device has a device owner.
3683 assertTrue(dpm.isDeviceManaged());
3684 mContext.binder.callingUid = 1234567;
3685 mContext.callerPermissions.add(permission.MANAGE_USERS);
3686 assertTrue(dpm.isDeviceManaged());
3687 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3688 mContext.binder.clearCallingIdentity();
3689 assertTrue(dpm.isDeviceManaged());
3690
3691 clearDeviceOwner();
3692
3693 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3694 // not have a device owner.
3695 mContext.binder.callingUid = 1234567;
3696 mContext.callerPermissions.add(permission.MANAGE_USERS);
3697 assertFalse(dpm.isDeviceManaged());
3698 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3699 mContext.binder.clearCallingIdentity();
3700 assertFalse(dpm.isDeviceManaged());
3701 }
3702
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003703 public void testDeviceOwnerOrganizationName() throws Exception {
3704 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3705 setupDeviceOwner();
3706
3707 dpm.setOrganizationName(admin1, "organization");
3708
3709 // Device owner can retrieve organization managing the device.
3710 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3711
3712 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3713 mContext.binder.callingUid = 1234567;
3714 mContext.callerPermissions.add(permission.MANAGE_USERS);
3715 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3716 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3717
3718 // System can retrieve organization managing the device.
3719 mContext.binder.clearCallingIdentity();
3720 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3721
3722 // Removing the device owner clears the organization managing the device.
3723 clearDeviceOwner();
3724 assertNull(dpm.getDeviceOwnerOrganizationName());
3725 }
3726
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003727 public void testWipeDataManagedProfile() throws Exception {
3728 final int MANAGED_PROFILE_USER_ID = 15;
3729 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3730 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3731 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
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));
yuemingwf7f67dc2017-09-08 14:23:53 +01003736 // Get mock reason string since we throw an IAE with empty string input.
3737 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3738 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003739
3740 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003741 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003742 MANAGED_PROFILE_USER_ID);
3743 }
3744
3745 public void testWipeDataManagedProfileDisallowed() throws Exception {
3746 final int MANAGED_PROFILE_USER_ID = 15;
3747 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3748 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3749
3750 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003751 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003752 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3753
Pavel Grafov75c0a892017-05-18 17:28:27 +01003754 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003755 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3756 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3757 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003758 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3759 thenReturn("Just a test string.");
3760
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003761 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003762 // The PO is not allowed to remove the profile if the user restriction was set on the
3763 // profile by the system
3764 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3765 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003766 }
3767
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003768 public void testWipeDataDeviceOwner() throws Exception {
3769 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003770 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003771 UserManager.DISALLOW_FACTORY_RESET,
3772 UserHandle.SYSTEM))
3773 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003774 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3775 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003776
3777 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003778 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003779 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3780 /*wipeEuicc=*/ eq(false));
3781 }
3782
3783 public void testWipeEuiccDataEnabled() throws Exception {
3784 setDeviceOwner();
3785 when(getServices().userManager.getUserRestrictionSource(
3786 UserManager.DISALLOW_FACTORY_RESET,
3787 UserHandle.SYSTEM))
3788 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003789 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3790 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003791
3792 dpm.wipeData(WIPE_EUICC);
3793 verify(getServices().recoverySystem).rebootWipeUserData(
3794 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3795 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003796 }
3797
3798 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3799 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003800 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003801 UserManager.DISALLOW_FACTORY_RESET,
3802 UserHandle.SYSTEM))
3803 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003804 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3805 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003806 // The DO is not allowed to wipe the device if the user restriction was set
3807 // by the system
3808 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3809 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003810 }
3811
3812 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3813 final int MANAGED_PROFILE_USER_ID = 15;
3814 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3815 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3816
3817 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003818 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003819 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3820
Pavel Grafov75c0a892017-05-18 17:28:27 +01003821 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003822 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3823 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3824 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3825
3826 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3827 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3828
3829 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3830 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3831 // Failed password attempts on the parent user are taken into account, as there isn't a
3832 // separate work challenge.
3833 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3834 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3835 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3836
3837 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3838 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003839 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003840 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003841 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003842 }
3843
3844 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3845 throws Exception {
3846 final int MANAGED_PROFILE_USER_ID = 15;
3847 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3848 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3849
3850 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003851 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003852 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3853
Pavel Grafov75c0a892017-05-18 17:28:27 +01003854 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003855 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3856 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3857 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3858
3859 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3860 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3861
3862 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3863 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3864 // Failed password attempts on the parent user are taken into account, as there isn't a
3865 // separate work challenge.
3866 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3867 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3868 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3869
3870 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3871 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003872 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003873 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003874 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003875 }
3876
3877 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3878 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003879 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003880 UserManager.DISALLOW_FACTORY_RESET,
3881 UserHandle.SYSTEM))
3882 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3883
3884 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3885
3886 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3887 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3888 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3889 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3890 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3891
3892 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3893 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003894 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003895 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3896 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003897 }
3898
3899 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3900 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003901 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003902 UserManager.DISALLOW_FACTORY_RESET,
3903 UserHandle.SYSTEM))
3904 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3905
3906 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3907
3908 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3909 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3910 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3911 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3912 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3913
3914 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003915 verifyZeroInteractions(getServices().recoverySystem);
3916 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003917 .removeUserEvenWhenDisallowed(anyInt());
3918 }
3919
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003920 public void testGetPermissionGrantState() throws Exception {
3921 final String permission = "some.permission";
3922 final String app1 = "com.example.app1";
3923 final String app2 = "com.example.app2";
3924
Pavel Grafov75c0a892017-05-18 17:28:27 +01003925 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003926 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003927 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003928 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003929 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003930 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3931 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003932 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003933 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003934 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003935 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003936 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003937 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3938
3939 // System can retrieve permission grant state.
3940 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003941 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003942 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3943 dpm.getPermissionGrantState(null, app1, permission));
3944 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3945 dpm.getPermissionGrantState(null, app2, permission));
3946
3947 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003948 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3949 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003950 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3951 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003952
3953 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003954 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3955 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003956 setAsProfileOwner(admin1);
3957 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3958 dpm.getPermissionGrantState(admin1, app1, permission));
3959 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3960 dpm.getPermissionGrantState(admin1, app2, permission));
3961 }
3962
Rubin Xuaab7a412016-12-30 21:13:29 +00003963 public void testResetPasswordWithToken() throws Exception {
3964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3965 setupDeviceOwner();
3966 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003967 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3968 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3969
Rubin Xuaab7a412016-12-30 21:13:29 +00003970 // test adding a token
3971 final byte[] token = new byte[32];
3972 final long handle = 123456;
3973 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003974 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003975 .thenReturn(handle);
3976 assertTrue(dpm.setResetPasswordToken(admin1, token));
3977
3978 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003979 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003980 .thenReturn(true);
3981 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3982
3983 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003984 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003985 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3986 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003987 eq(UserHandle.USER_SYSTEM)))
3988 .thenReturn(true);
3989 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3990
3991 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003992 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003993 .thenReturn(true);
3994 assertTrue(dpm.clearResetPasswordToken(admin1));
3995 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003996
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01003997 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
3998 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3999 () -> dpm.setPasswordBlacklist(admin1, null, null));
4000 verifyZeroInteractions(getServices().passwordBlacklist);
4001 }
4002
4003 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4004 setupProfileOwner();
4005 dpm.setPasswordBlacklist(admin1, null, null);
4006 verifyZeroInteractions(getServices().passwordBlacklist);
4007 }
4008
4009 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4010 final String name = "myblacklist";
4011 final List<String> explicit = Arrays.asList("password", "letmein");
4012 setupProfileOwner();
4013 dpm.setPasswordBlacklist(admin1, name, explicit);
4014 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4015 }
4016
4017 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4018 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4019 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4020 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4021 setupDeviceOwner();
4022 final String name = "Name of the Blacklist";
4023 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4024 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4025 }
4026
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004027 public void testIsActivePasswordSufficient() throws Exception {
4028 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4029 mContext.packageName = admin1.getPackageName();
4030 setupDeviceOwner();
4031
4032 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4033 dpm.setPasswordMinimumLength(admin1, 8);
4034 dpm.setPasswordMinimumLetters(admin1, 6);
4035 dpm.setPasswordMinimumLowerCase(admin1, 3);
4036 dpm.setPasswordMinimumUpperCase(admin1, 1);
4037 dpm.setPasswordMinimumNonLetter(admin1, 1);
4038 dpm.setPasswordMinimumNumeric(admin1, 1);
4039 dpm.setPasswordMinimumSymbols(admin1, 0);
4040
Rubin Xucc391c22018-01-02 20:37:35 +00004041 reset(mContext.spiedContext);
4042
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004043 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4044 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4045 8, 2,
4046 6, 1,
4047 0, 1);
4048
4049 setActivePasswordState(passwordMetricsNoSymbols);
4050 assertTrue(dpm.isActivePasswordSufficient());
4051
4052 initializeDpms();
4053 reset(mContext.spiedContext);
4054 assertTrue(dpm.isActivePasswordSufficient());
4055
4056 // This call simulates the user entering the password for the first time after a reboot.
4057 // This causes password metrics to be reloaded into memory. Until this happens,
4058 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4059 // even if the DPC changes password requirements so that the password no longer meets the
4060 // requirements. This is a known limitation of the current implementation of
4061 // isActivePasswordSufficient() - see b/34218769.
4062 setActivePasswordState(passwordMetricsNoSymbols);
4063 assertTrue(dpm.isActivePasswordSufficient());
4064
4065 dpm.setPasswordMinimumSymbols(admin1, 1);
4066 // This assertion would fail if we had not called setActivePasswordState() again after
4067 // initializeDpms() - see previous comment.
4068 assertFalse(dpm.isActivePasswordSufficient());
4069
4070 initializeDpms();
4071 reset(mContext.spiedContext);
4072 assertFalse(dpm.isActivePasswordSufficient());
4073
4074 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4075 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4076 7, 2,
4077 5, 1,
4078 1, 2);
4079
4080 setActivePasswordState(passwordMetricsWithSymbols);
4081 assertTrue(dpm.isActivePasswordSufficient());
4082 }
4083
Pavel Grafov75c0a892017-05-18 17:28:27 +01004084 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4085 throws Exception {
4086 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004087 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004088
Pavel Grafov75c0a892017-05-18 17:28:27 +01004089 dpm.setActivePasswordState(passwordMetrics, userHandle);
4090 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004091
Rubin Xucc391c22018-01-02 20:37:35 +00004092 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4093 // reportPasswordChanged()
4094 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4095 MockUtils.checkIntentAction(
4096 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4097 MockUtils.checkUserHandle(userHandle));
4098
Pavel Grafov75c0a892017-05-18 17:28:27 +01004099 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4100 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004101 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004102
4103 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4104 MockUtils.checkIntent(intent),
4105 MockUtils.checkUserHandle(userHandle));
4106
4107 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4108 // let it finish with system uid, otherwise it will throw and crash.
4109 flushTasks();
4110
4111 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004112 }
4113
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004114 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4115 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4116 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4117 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4118 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4119 DpmMockContext.SYSTEM_UID);
4120 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4121 DpmMockContext.SYSTEM_UID);
4122
4123 // Set up a device owner.
4124 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004125 setupDeviceOwner();
4126
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004127 // First and second user set IMEs manually.
4128 mContext.binder.callingUid = firstUserSystemUid;
4129 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4130 mContext.binder.callingUid = secondUserSystemUid;
4131 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004132
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004133 // Device owner changes IME for first user.
4134 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004135 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004136 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004137 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004138 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004139 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004140 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004141 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4142 mContext.binder.callingUid = firstUserSystemUid;
4143 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4144 mContext.binder.callingUid = secondUserSystemUid;
4145 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004146
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004147 // Second user changes IME manually.
4148 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4149 mContext.binder.callingUid = firstUserSystemUid;
4150 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4151 mContext.binder.callingUid = secondUserSystemUid;
4152 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004153
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004154 // First user changes IME manually.
4155 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4156 mContext.binder.callingUid = firstUserSystemUid;
4157 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4158 mContext.binder.callingUid = secondUserSystemUid;
4159 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004160
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004161 // Device owner changes IME for first user again.
4162 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004164 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004165 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004166 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004167 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004168 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4169 mContext.binder.callingUid = firstUserSystemUid;
4170 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4171 mContext.binder.callingUid = secondUserSystemUid;
4172 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004173
4174 // Restarting the DPMS should not lose information.
4175 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004176 mContext.binder.callingUid = firstUserSystemUid;
4177 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4178 mContext.binder.callingUid = secondUserSystemUid;
4179 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004180
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004181 // Device owner can find out whether it set the current IME itself.
4182 mContext.binder.callingUid = deviceOwnerUid;
4183 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004184
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004185 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004186 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004187 mContext.binder.callingUid = firstUserSystemUid;
4188 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4189 mContext.binder.callingUid = secondUserSystemUid;
4190 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004191 }
4192
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004193 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4194 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4195 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4196 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4197 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4198 DpmMockContext.SYSTEM_UID);
4199 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4200 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004201
4202 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004203 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004204 setupProfileOwner();
4205
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004206 // First and second user set IMEs manually.
4207 mContext.binder.callingUid = firstUserSystemUid;
4208 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4209 mContext.binder.callingUid = secondUserSystemUid;
4210 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004211
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004212 // Profile owner changes IME for second user.
4213 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004214 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004215 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004216 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004217 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004218 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004219 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004220 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4221 mContext.binder.callingUid = firstUserSystemUid;
4222 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4223 mContext.binder.callingUid = secondUserSystemUid;
4224 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004225
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004226 // First user changes IME manually.
4227 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4228 mContext.binder.callingUid = firstUserSystemUid;
4229 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4230 mContext.binder.callingUid = secondUserSystemUid;
4231 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004232
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004233 // Second user changes IME manually.
4234 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4235 mContext.binder.callingUid = firstUserSystemUid;
4236 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4237 mContext.binder.callingUid = secondUserSystemUid;
4238 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004239
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004240 // Profile owner changes IME for second user again.
4241 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004242 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004243 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004244 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004245 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004246 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004247 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4248 mContext.binder.callingUid = firstUserSystemUid;
4249 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4250 mContext.binder.callingUid = secondUserSystemUid;
4251 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004252
4253 // Restarting the DPMS should not lose information.
4254 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004255 mContext.binder.callingUid = firstUserSystemUid;
4256 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4257 mContext.binder.callingUid = secondUserSystemUid;
4258 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004259
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004260 // Profile owner can find out whether it set the current IME itself.
4261 mContext.binder.callingUid = profileOwnerUid;
4262 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004263
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004264 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004265 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004266 mContext.binder.callingUid = firstUserSystemUid;
4267 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4268 mContext.binder.callingUid = secondUserSystemUid;
4269 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004270 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004271
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004272 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4273 throws Exception {
4274 // Set up a device owner.
4275 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4276 setupDeviceOwner();
4277 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4278 }
4279
4280 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4281 throws Exception {
4282 // Set up a profile owner.
4283 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4284 setupProfileOwner();
4285 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4286 }
4287
4288 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4289 int adminUid) throws Exception {
4290 mContext.binder.callingUid = adminUid;
4291 final int userId = UserHandle.getUserId(adminUid);
4292
4293 final String packageName = "some.package";
4294 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4295 admin1, Collections.singletonList(packageName)));
4296 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4297
4298 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4299 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4300
4301 // Attempt to set to empty list (which means no listener is whitelisted)
4302 mContext.binder.callingUid = adminUid;
4303 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004304 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004305 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4306
4307 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4308 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4309 }
4310
4311 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4312 // Set up a managed profile
4313 final int MANAGED_PROFILE_USER_ID = 15;
4314 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4315 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4316 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4317
4318 final String permittedListener = "some.package";
4319 setupPackageInPackageManager(
4320 permittedListener,
4321 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4322 /*appId=*/ 12345, /*flags=*/ 0);
4323
4324 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4325 admin1, Collections.singletonList(permittedListener)));
4326
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004327 // isNotificationListenerServicePermitted should throw if not called from System.
4328 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4329 () -> dpms.isNotificationListenerServicePermitted(
4330 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004331
4332 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4333 assertTrue(dpms.isNotificationListenerServicePermitted(
4334 permittedListener, MANAGED_PROFILE_USER_ID));
4335 }
4336
4337 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4338 throws Exception {
4339 // Set up a managed profile
4340 final int MANAGED_PROFILE_USER_ID = 15;
4341 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4342 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4343 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4344
4345 final String permittedListener = "permitted.package";
4346 int appId = 12345;
4347 setupPackageInPackageManager(
4348 permittedListener,
4349 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4350 appId, /*flags=*/ 0);
4351
4352 final String notPermittedListener = "not.permitted.package";
4353 setupPackageInPackageManager(
4354 notPermittedListener,
4355 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4356 ++appId, /*flags=*/ 0);
4357
4358 final String systemListener = "system.package";
4359 setupPackageInPackageManager(
4360 systemListener,
4361 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4362 ++appId, ApplicationInfo.FLAG_SYSTEM);
4363
4364 // By default all packages are allowed
4365 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4366
4367 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4368 assertTrue(dpms.isNotificationListenerServicePermitted(
4369 permittedListener, MANAGED_PROFILE_USER_ID));
4370 assertTrue(dpms.isNotificationListenerServicePermitted(
4371 notPermittedListener, MANAGED_PROFILE_USER_ID));
4372 assertTrue(dpms.isNotificationListenerServicePermitted(
4373 systemListener, MANAGED_PROFILE_USER_ID));
4374
4375 // Setting only one package in the whitelist
4376 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4377 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4378 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004379 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004380 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4381 assertEquals(1, permittedListeners.size());
4382 assertEquals(permittedListener, permittedListeners.get(0));
4383
4384 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4385 assertTrue(dpms.isNotificationListenerServicePermitted(
4386 permittedListener, MANAGED_PROFILE_USER_ID));
4387 assertFalse(dpms.isNotificationListenerServicePermitted(
4388 notPermittedListener, MANAGED_PROFILE_USER_ID));
4389 // System packages are always allowed (even if not in the whitelist)
4390 assertTrue(dpms.isNotificationListenerServicePermitted(
4391 systemListener, MANAGED_PROFILE_USER_ID));
4392
4393 // Setting an empty whitelist - only system listeners allowed
4394 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4395 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004396 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004397 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4398
4399 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4400 assertFalse(dpms.isNotificationListenerServicePermitted(
4401 permittedListener, MANAGED_PROFILE_USER_ID));
4402 assertFalse(dpms.isNotificationListenerServicePermitted(
4403 notPermittedListener, MANAGED_PROFILE_USER_ID));
4404 // System packages are always allowed (even if not in the whitelist)
4405 assertTrue(dpms.isNotificationListenerServicePermitted(
4406 systemListener, MANAGED_PROFILE_USER_ID));
4407
4408 // Setting a null whitelist - all listeners allowed
4409 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4410 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4411 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4412
4413 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4414 assertTrue(dpms.isNotificationListenerServicePermitted(
4415 permittedListener, MANAGED_PROFILE_USER_ID));
4416 assertTrue(dpms.isNotificationListenerServicePermitted(
4417 notPermittedListener, MANAGED_PROFILE_USER_ID));
4418 assertTrue(dpms.isNotificationListenerServicePermitted(
4419 systemListener, MANAGED_PROFILE_USER_ID));
4420 }
4421
4422 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4423 throws Exception {
4424 // Set up a managed profile
4425 final int MANAGED_PROFILE_USER_ID = 15;
4426 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4427 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4428 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4429
4430 final String nonSystemPackage = "non.system.package";
4431 int appId = 12345;
4432 setupPackageInPackageManager(
4433 nonSystemPackage,
4434 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4435 appId, /*flags=*/ 0);
4436
4437 final String systemListener = "system.package";
4438 setupPackageInPackageManager(
4439 systemListener,
4440 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4441 ++appId, ApplicationInfo.FLAG_SYSTEM);
4442
4443 // By default all packages are allowed (for all profiles)
4444 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4445
4446 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4447 assertTrue(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 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4457 // all allowed in primary profile
4458 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4459 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004460 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004461 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4462
4463 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4464 assertFalse(dpms.isNotificationListenerServicePermitted(
4465 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4466 assertTrue(dpms.isNotificationListenerServicePermitted(
4467 systemListener, MANAGED_PROFILE_USER_ID));
4468 assertTrue(dpms.isNotificationListenerServicePermitted(
4469 nonSystemPackage, UserHandle.USER_SYSTEM));
4470 assertTrue(dpms.isNotificationListenerServicePermitted(
4471 systemListener, UserHandle.USER_SYSTEM));
4472 }
4473
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004474 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004475 mServiceContext.packageName = mRealTestContext.getPackageName();
4476 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4477 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004478 setDeviceOwner();
4479
Pavel Grafov75c0a892017-05-18 17:28:27 +01004480 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004481 }
4482
4483 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004484 mServiceContext.packageName = mRealTestContext.getPackageName();
4485 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4486 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004487 setAsProfileOwner(admin1);
4488
Pavel Grafov75c0a892017-05-18 17:28:27 +01004489 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4490 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004491 }
4492
4493 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004494 mServiceContext.packageName = mRealTestContext.getPackageName();
4495 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4496 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004497 setAsProfileOwner(admin1);
4498
Pavel Grafov75c0a892017-05-18 17:28:27 +01004499 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4500 caller.packageName = "com.example.delegate";
4501 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4502 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004503
Pavel Grafov75c0a892017-05-18 17:28:27 +01004504 // Make caller a delegated cert installer.
4505 runAsCaller(mAdmin1Context, dpms,
4506 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004507
4508 verifyCanGetOwnerInstalledCaCerts(null, caller);
4509 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004510 }
4511
Rubin Xucc391c22018-01-02 20:37:35 +00004512 public void testDisallowSharingIntoProfileSetRestriction() {
4513 Bundle restriction = new Bundle();
4514 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4515
4516 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4517 RestrictionsListener listener = new RestrictionsListener(mContext);
4518 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4519 new Bundle());
4520 verifyDataSharingChangedBroadcast();
4521 }
4522
4523 public void testDisallowSharingIntoProfileClearRestriction() {
4524 Bundle restriction = new Bundle();
4525 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4526
4527 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4528 RestrictionsListener listener = new RestrictionsListener(mContext);
4529 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4530 restriction);
4531 verifyDataSharingChangedBroadcast();
4532 }
4533
4534 public void testDisallowSharingIntoProfileUnchanged() {
4535 RestrictionsListener listener = new RestrictionsListener(mContext);
4536 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4537 new Bundle());
4538 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4539 }
4540
4541 private void verifyDataSharingChangedBroadcast() {
4542 Intent expectedIntent = new Intent(
4543 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4544 expectedIntent.setPackage("com.android.managedprovisioning");
4545 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4546 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4547 MockUtils.checkIntent(expectedIntent),
4548 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4549 }
4550
Robin Lee2c68dad2017-03-17 12:50:24 +00004551 private void verifyCanGetOwnerInstalledCaCerts(
4552 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004553 final String alias = "cert";
4554 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004555
4556 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004557 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004558 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4559 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004560 }
4561 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4562
4563 // caller: device admin or delegated certificate installer
4564 callerContext.applicationInfo = new ApplicationInfo();
4565 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4566
4567 // system_server
4568 final DpmMockContext serviceContext = mContext;
4569 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004570 getServices().addPackageContext(callerUser, admin1Context);
4571 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004572
4573 // Install a CA cert.
4574 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004575 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004576 .thenReturn(alias);
4577 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004578 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004579 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004580 });
4581
Pavel Grafov75c0a892017-05-18 17:28:27 +01004582 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4583 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4584 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004585 flushTasks();
4586
Robin Lee2c68dad2017-03-17 12:50:24 +00004587 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4588
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004589 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004590 runAsCaller(admin1Context, dpms, (dpm) -> {
4591 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004592 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004593 ownerInstalledCaCerts.addAll(installedCaCerts);
4594 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004595
4596 // Restarting the DPMS should not lose information.
4597 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004598 runAsCaller(admin1Context, dpms, (dpm) ->
4599 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004600
4601 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004602 runAsCaller(serviceContext, dpms, (dpm) -> {
4603 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004604
Robin Lee2c68dad2017-03-17 12:50:24 +00004605 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004606 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004607 });
4608
Pavel Grafov75c0a892017-05-18 17:28:27 +01004609 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4610 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4611 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004612 flushTasks();
4613
4614 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4615 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004616 runAsCaller(admin1Context, dpms, (dpm) -> {
4617 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4618 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004619 }
4620
Robin Lee2c68dad2017-03-17 12:50:24 +00004621 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4622 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004623 final String alias = "cert";
4624 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004625
4626 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004627 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004628 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4629 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004630 }
4631 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4632
4633 // caller: device admin or delegated certificate installer
4634 callerContext.applicationInfo = new ApplicationInfo();
4635 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4636
4637 // system_server
4638 final DpmMockContext serviceContext = mContext;
4639 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004640 getServices().addPackageContext(callerUser, admin1Context);
4641 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004642
4643 // Install a CA cert as caller
4644 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004645 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004646 .thenReturn(alias);
4647 assertTrue(dpm.installCaCert(callerName, caCert));
4648 });
4649
4650 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004651 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004652 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004653 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4654 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4655 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004656 flushTasks();
4657
Robin Lee2c68dad2017-03-17 12:50:24 +00004658 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004659 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004660
4661 runAsCaller(serviceContext, dpms, (dpm) -> {
4662 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4663 assertNotNull(ownerInstalledCaCerts);
4664 assertTrue(ownerInstalledCaCerts.isEmpty());
4665 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004666 }
4667
Eran Messeri94d56762017-12-21 20:50:54 +00004668 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4669 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4670 Arrays.sort(gotFlags);
4671 Arrays.sort(expectedFlags);
4672 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4673 }
4674
4675 public void testTranslationOfIdAttestationFlag() {
4676 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4677 int[] correspondingAttUtilsTypes = new int[]{
4678 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4679 AttestationUtils.ID_TYPE_MEID};
4680
4681 // Test translation of zero flags
4682 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4683
4684 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4685 // non-null array
4686 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4687
4688 // Test translation of a single flag
4689 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4690 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4691 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4692
4693 // Test translation of two flags
4694 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4695 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4696 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4697 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4698
4699 // Test translation of all three flags
4700 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4701 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4702 AttestationUtils.ID_TYPE_MEID});
4703 // Test translation of all three flags
4704 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4705 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4706 AttestationUtils.ID_TYPE_MEID});
4707 }
4708
Victor Chang3e794af2016-03-04 13:48:17 +00004709 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004710 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004711 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4712 dpms.notifyChangeToContentObserver(
4713 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4714 }
4715
4716 private void assertProvisioningAllowed(String action, boolean expected) {
4717 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4718 dpm.isProvisioningAllowed(action));
4719 }
Tony Mak2f26b792016-11-28 17:54:51 +00004720
Nicolas Prevot45d29072017-01-18 16:11:19 +00004721 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4722 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004723 final String previousPackageName = mContext.packageName;
4724 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004725
4726 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4727 mContext.packageName = packageName;
4728 mMockContext.binder.callingUid = uid;
4729 assertProvisioningAllowed(action, expected);
4730
4731 // Set the previous package name / calling uid to go back to the initial state.
4732 mContext.packageName = previousPackageName;
4733 mMockContext.binder.callingUid = previousUid;
4734 }
4735
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004736 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004737 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4738 }
4739
4740 private void assertCheckProvisioningPreCondition(
4741 String action, String packageName, int provisioningCondition) {
4742 assertEquals("checkProvisioningPreCondition("
4743 + action + ", " + packageName + ") returning unexpected result",
4744 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004745 }
4746
Tony Mak2f26b792016-11-28 17:54:51 +00004747 /**
4748 * Setup a managed profile with the specified admin and its uid.
4749 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4750 * @param adminUid uid of the admin package.
4751 * @param copyFromAdmin package information for {@code admin} will be built based on this
4752 * component's information.
4753 */
4754 private void addManagedProfile(
4755 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4756 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004757 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004758 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4759 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4760 dpm.setActiveAdmin(admin, false, userId);
4761 assertTrue(dpm.setProfileOwner(admin, null, userId));
4762 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4763 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004764
4765 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004766 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004767 */
Robin Leeabaa0692017-02-20 20:54:22 +00004768 private static StringParceledListSlice asSlice(String[] s) {
4769 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004770 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004771
4772 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004773 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4774 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004775
Robin Lee2c68dad2017-03-17 12:50:24 +00004776 // We can't let exceptions happen on the background thread. Throw them here if they happen
4777 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004778 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004779 }
Victor Chang3e794af2016-03-04 13:48:17 +00004780}