blob: a2622a7a5957a3c45b61d06335442eb9da218a62 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
53import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000054import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070055import android.app.admin.DeviceAdminReceiver;
56import android.app.admin.DevicePolicyManager;
57import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010058import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000061import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000062import android.content.pm.ApplicationInfo;
63import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010065import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000066import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010068import android.graphics.Color;
69import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080070import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080071import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080073import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070075import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010076import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080077import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010078import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000079import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000080import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080081import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000082import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010083import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070085
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000087import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000088import com.android.server.LocalServices;
89import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000090import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000091import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000092
Robin Lee7f5c91c2017-02-08 21:27:02 +000093import org.hamcrest.BaseMatcher;
94import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080095import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070096import org.mockito.invocation.InvocationOnMock;
97import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
Makoto Onukic8a5a552015-11-19 14:29:12 -080099import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000101import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700102import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700104import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100105import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000106import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700109 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000110 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 m FrameworksServicesTests &&
112 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000113 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800115 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116
117 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000118 *
119 * , or:
120 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000122@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100123@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000125 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
126 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
127 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100128 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
129 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000130
Pavel Grafov75c0a892017-05-18 17:28:27 +0100131 // TODO replace all instances of this with explicit {@link #mServiceContext}.
132 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100134
135 private DpmMockContext mServiceContext;
136 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700137 public DevicePolicyManager dpm;
138 public DevicePolicyManagerServiceTestable dpms;
139
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100140 /*
141 * The CA cert below is the content of cacert.pem as generated by:
142 *
143 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
144 */
145 private static final String TEST_CA =
146 "-----BEGIN CERTIFICATE-----\n" +
147 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
148 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
149 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
150 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
151 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
152 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
153 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
154 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
155 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
156 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
157 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
158 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
159 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
160 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
161 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
162 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
163 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
164 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
165 "wQ==\n" +
166 "-----END CERTIFICATE-----\n";
167
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700168 @Override
169 protected void setUp() throws Exception {
170 super.setUp();
171
172 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100173 mServiceContext = mContext;
174 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
175 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700176 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100177 doReturn(Collections.singletonList(new ResolveInfo()))
178 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
179 any(Intent.class),
180 anyInt(),
181 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700182
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800183 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100184 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800185
Makoto Onukia52562c2015-10-01 16:12:31 -0700186 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700187
Sudheer Shanka101c3532018-01-08 16:28:42 -0800188 Mockito.reset(getServices().usageStatsManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700189 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
190 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
191 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800192 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700193
Pavel Grafov75c0a892017-05-18 17:28:27 +0100194 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
195 mAdmin1Context.packageName = admin1.getPackageName();
196 mAdmin1Context.applicationInfo = new ApplicationInfo();
197 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
198
Makoto Onukib643fb02015-09-22 15:03:44 -0700199 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700200 }
201
Robin Lee2c68dad2017-03-17 12:50:24 +0000202 @Override
203 protected void tearDown() throws Exception {
204 flushTasks();
205 super.tearDown();
206 }
207
Makoto Onukia52562c2015-10-01 16:12:31 -0700208 private void initializeDpms() {
209 // Need clearCallingIdentity() to pass permission checks.
210 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100211 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700212
Pavel Grafov75c0a892017-05-18 17:28:27 +0100213 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
Sudheer Shanka101c3532018-01-08 16:28:42 -0800214 dpms.handleStart();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100215 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
216 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700217
Pavel Grafov75c0a892017-05-18 17:28:27 +0100218 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700219
Pavel Grafov75c0a892017-05-18 17:28:27 +0100220 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700221 }
222
Makoto Onukib643fb02015-09-22 15:03:44 -0700223 private void setUpUserManager() {
224 // Emulate UserManager.set/getApplicationRestriction().
225 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
226
227 // UM.setApplicationRestrictions() will save to appRestrictions.
228 doAnswer(new Answer<Void>() {
229 @Override
230 public Void answer(InvocationOnMock invocation) throws Throwable {
231 String pkg = (String) invocation.getArguments()[0];
232 Bundle bundle = (Bundle) invocation.getArguments()[1];
233 UserHandle user = (UserHandle) invocation.getArguments()[2];
234
235 appRestrictions.put(Pair.create(pkg, user), bundle);
236
237 return null;
238 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100240 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700241
242 // UM.getApplicationRestrictions() will read from appRestrictions.
243 doAnswer(new Answer<Bundle>() {
244 @Override
245 public Bundle answer(InvocationOnMock invocation) throws Throwable {
246 String pkg = (String) invocation.getArguments()[0];
247 UserHandle user = (UserHandle) invocation.getArguments()[1];
248
249 return appRestrictions.get(Pair.create(pkg, user));
250 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100251 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700252 anyString(), any(UserHandle.class));
253
Makoto Onukid932f762015-09-29 16:53:38 -0700254 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100255 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700256 }
257
258 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100259 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700260
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 mServiceContext.binder.callingUid =
262 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
263 runAsCaller(mServiceContext, dpms, dpm -> {
264 // PO needs to be a DA.
265 dpm.setActiveAdmin(admin, /*replace=*/ false);
266 // Fire!
267 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
268 // Check
269 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
270 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700271
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700273 }
274
275 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100276 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700277 .thenReturn(false);
278
279 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100280 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700281
282 // If the device has no DPMS feature, it shouldn't register the local service.
283 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
284 }
285
Sudheer Shanka101c3532018-01-08 16:28:42 -0800286 public void testHandleStart() throws Exception {
287 // Device owner in SYSTEM_USER
288 setDeviceOwner();
289 // Profile owner in CALLER_USER_HANDLE
290 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
291 setAsProfileOwner(admin2);
292 // Active admin in CALLER_USER_HANDLE
293 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
294 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
295 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
296 DpmMockContext.CALLER_USER_HANDLE);
297 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
298 DpmMockContext.CALLER_USER_HANDLE));
299
300 initializeDpms();
301
302 // Verify
303 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
304 MockUtils.checkAdminApps(admin1.getPackageName()),
305 eq(UserHandle.USER_SYSTEM));
306 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
307 MockUtils.checkAdminApps(admin2.getPackageName(),
308 adminAnotherPackage.getPackageName()),
309 eq(DpmMockContext.CALLER_USER_HANDLE));
310 }
311
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700312 /**
313 * Caller doesn't have proper permissions.
314 */
315 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700316 // 1. Failure cases.
317
318 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100319 assertExpectException(SecurityException.class, /* messageRegex= */ null,
320 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700321
322 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
323 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100324
325 assertExpectException(SecurityException.class, /* messageRegex= */ null,
326 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700327 }
328
Makoto Onukif76b06a2015-09-22 15:03:44 -0700329 /**
330 * Test for:
331 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800332 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700333 * {@link DevicePolicyManager#isAdminActive}
334 * {@link DevicePolicyManager#isAdminActiveAsUser}
335 * {@link DevicePolicyManager#getActiveAdmins}
336 * {@link DevicePolicyManager#getActiveAdminsAsUser}
337 */
338 public void testSetActiveAdmin() throws Exception {
339 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700340 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
341
Makoto Onukif76b06a2015-09-22 15:03:44 -0700342 // 2. Call the API.
343 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344
345 // 3. Verify internal calls.
346
347 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700348 verify(mContext.spiedContext).sendBroadcastAsUser(
349 MockUtils.checkIntentAction(
350 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
351 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
352 verify(mContext.spiedContext).sendBroadcastAsUser(
353 MockUtils.checkIntentAction(
354 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700355 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
356
Pavel Grafov75c0a892017-05-18 17:28:27 +0100357 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700358 eq(admin1.getPackageName()),
359 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
360 eq(PackageManager.DONT_KILL_APP),
361 eq(DpmMockContext.CALLER_USER_HANDLE),
362 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700363
Sudheer Shanka101c3532018-01-08 16:28:42 -0800364 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
365 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
366
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700367 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700368
369 // Make sure it's active admin1.
370 assertTrue(dpm.isAdminActive(admin1));
371 assertFalse(dpm.isAdminActive(admin2));
372 assertFalse(dpm.isAdminActive(admin3));
373
374 // But not admin1 for a different user.
375
376 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
377 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
378 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
379
380 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
381 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
382
383 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
384
385 // Next, add one more admin.
386 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700387 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700388 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389
390 dpm.setActiveAdmin(admin2, /* replace =*/ false);
391
392 // Now we have two admins.
393 assertTrue(dpm.isAdminActive(admin1));
394 assertTrue(dpm.isAdminActive(admin2));
395 assertFalse(dpm.isAdminActive(admin3));
396
397 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
398 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100399 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700400 eq(admin1.getPackageName()),
401 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
402 eq(PackageManager.DONT_KILL_APP),
403 eq(DpmMockContext.CALLER_USER_HANDLE),
404 anyString());
405
Sudheer Shanka101c3532018-01-08 16:28:42 -0800406 // times(2) because it was previously called for admin1 which is in the same package
407 // as admin2.
408 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
409 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
410
Makoto Onukif76b06a2015-09-22 15:03:44 -0700411 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100412 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
413 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700414
415 // 5. Add the same admin1 again with replace, which should succeed.
416 dpm.setActiveAdmin(admin1, /* replace =*/ true);
417
418 // TODO make sure it's replaced.
419
420 // 6. Test getActiveAdmins()
421 List<ComponentName> admins = dpm.getActiveAdmins();
422 assertEquals(2, admins.size());
423 assertEquals(admin1, admins.get(0));
424 assertEquals(admin2, admins.get(1));
425
Sudheer Shanka101c3532018-01-08 16:28:42 -0800426 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
427 // replaced
428 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
429
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 // Another user has no admins.
431 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
432
433 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
434 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
435
436 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
437 }
438
Makoto Onukid932f762015-09-29 16:53:38 -0700439 public void testSetActiveAdmin_multiUsers() throws Exception {
440
441 final int ANOTHER_USER_ID = 100;
442 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
443
Pavel Grafov75c0a892017-05-18 17:28:27 +0100444 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700445
446 // Set up pacakge manager for the other user.
447 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700448
449 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
450
451 dpm.setActiveAdmin(admin1, /* replace =*/ false);
452
453 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
454 dpm.setActiveAdmin(admin2, /* replace =*/ false);
455
456
457 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
458 assertTrue(dpm.isAdminActive(admin1));
459 assertFalse(dpm.isAdminActive(admin2));
460
461 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
462 assertFalse(dpm.isAdminActive(admin1));
463 assertTrue(dpm.isAdminActive(admin2));
464 }
465
Makoto Onukif76b06a2015-09-22 15:03:44 -0700466 /**
467 * Test for:
468 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800469 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700470 */
471 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
472 // 1. Make sure the caller has proper permissions.
473 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
474
475 dpm.setActiveAdmin(admin1, /* replace =*/ false);
476 assertTrue(dpm.isAdminActive(admin1));
477
478 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100479 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
480 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700481 }
482
483 /**
484 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800485 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
486 * BIND_DEVICE_ADMIN.
487 */
488 public void testSetActiveAdmin_permissionCheck() throws Exception {
489 // 1. Make sure the caller has proper permissions.
490 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
491
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100492 assertExpectException(IllegalArgumentException.class,
493 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
494 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800495 assertFalse(dpm.isAdminActive(adminNoPerm));
496
497 // Change the target API level to MNC. Now it can be set as DA.
498 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
499 VERSION_CODES.M);
500 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
501 assertTrue(dpm.isAdminActive(adminNoPerm));
502
503 // TODO Test the "load from the file" case where DA will still be loaded even without
504 // BIND_DEVICE_ADMIN and target API is N.
505 }
506
507 /**
508 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700509 * {@link DevicePolicyManager#removeActiveAdmin}
510 */
511 public void testRemoveActiveAdmin_SecurityException() {
512 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
513
514 // Add admin.
515
516 dpm.setActiveAdmin(admin1, /* replace =*/ false);
517
518 assertTrue(dpm.isAdminActive(admin1));
519
520 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
521
522 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
524 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700525
526 // Try to remove active admin with a different caller userid should fail too, without
527 // having MANAGE_DEVICE_ADMINS.
528 mContext.callerPermissions.clear();
529
Makoto Onukid932f762015-09-29 16:53:38 -0700530 // Change the caller, and call into DPMS directly with a different user-id.
531
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100533 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
534 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700535 }
536
537 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800538 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
539 * (because we can't send the remove broadcast).
540 */
541 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
542 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
543
544 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
545
546 // Add admin.
547
548 dpm.setActiveAdmin(admin1, /* replace =*/ false);
549
550 assertTrue(dpm.isAdminActive(admin1));
551
552 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
553
554 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100555 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800556 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100557 assertExpectException(IllegalStateException.class,
558 /* messageRegex= */ "User must be running and unlocked",
559 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800560
561 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800562 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
563 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800564
565 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100566 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800567 .thenReturn(true);
568
569 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700570 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800571 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
572 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800573 }
574
575 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700576 * Test for:
577 * {@link DevicePolicyManager#removeActiveAdmin}
578 */
Makoto Onukid932f762015-09-29 16:53:38 -0700579 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700580 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
581
582 // Add admin1.
583
584 dpm.setActiveAdmin(admin1, /* replace =*/ false);
585
586 assertTrue(dpm.isAdminActive(admin1));
587 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
588
589 // Different user, but should work, because caller has proper permissions.
590 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700591
592 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700593 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700594
595 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700596 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800597 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
598 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700599
600 // TODO DO Still can't be removed in this case.
601 }
602
603 /**
604 * Test for:
605 * {@link DevicePolicyManager#removeActiveAdmin}
606 */
607 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
608 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
609 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
610
611 // Add admin1.
612
613 dpm.setActiveAdmin(admin1, /* replace =*/ false);
614
615 assertTrue(dpm.isAdminActive(admin1));
616 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
617
618 // Broadcast from saveSettingsLocked().
619 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
620 MockUtils.checkIntentAction(
621 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
622 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
623
624 // Remove. No permissions, but same user, so it'll work.
625 mContext.callerPermissions.clear();
626 dpm.removeActiveAdmin(admin1);
627
Makoto Onukif76b06a2015-09-22 15:03:44 -0700628 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
629 MockUtils.checkIntentAction(
630 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
631 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
632 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700633 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700634 eq(dpms.mHandler),
635 eq(Activity.RESULT_OK),
636 isNull(String.class),
637 isNull(Bundle.class));
638
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700639 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800640 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
641 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700642
643 // Again broadcast from saveSettingsLocked().
644 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
645 MockUtils.checkIntentAction(
646 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
647 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
648
649 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700650 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700651
Sudheer Shanka101c3532018-01-08 16:28:42 -0800652 public void testRemoveActiveAdmin_multipleAdminsInUser() {
653 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
654 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
655
656 // Add admin1.
657 dpm.setActiveAdmin(admin1, /* replace =*/ false);
658
659 assertTrue(dpm.isAdminActive(admin1));
660 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
661
662 // Add admin2.
663 dpm.setActiveAdmin(admin2, /* replace =*/ false);
664
665 assertTrue(dpm.isAdminActive(admin2));
666 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
667
668 // Broadcast from saveSettingsLocked().
669 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
670 MockUtils.checkIntentAction(
671 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
672 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
673
674 // Remove. No permissions, but same user, so it'll work.
675 mContext.callerPermissions.clear();
676 dpm.removeActiveAdmin(admin1);
677
678 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
679 MockUtils.checkIntentAction(
680 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
681 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
682 isNull(String.class),
683 any(BroadcastReceiver.class),
684 eq(dpms.mHandler),
685 eq(Activity.RESULT_OK),
686 isNull(String.class),
687 isNull(Bundle.class));
688
689 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
690 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
691 MockUtils.checkAdminApps(admin2.getPackageName()),
692 eq(DpmMockContext.CALLER_USER_HANDLE));
693
694 // Again broadcast from saveSettingsLocked().
695 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
696 MockUtils.checkIntentAction(
697 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
698 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
699 }
700
701 /**
702 * Test for:
703 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
704 */
705 public void testForceRemoveActiveAdmin() throws Exception {
706 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
707
708 // Add admin.
709 setupPackageInPackageManager(admin1.getPackageName(),
710 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
711 /* appId= */ 10138,
712 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
713 dpm.setActiveAdmin(admin1, /* replace =*/ false);
714 assertTrue(dpm.isAdminActive(admin1));
715
716 // Calling from a non-shell uid should fail with a SecurityException
717 mContext.binder.callingUid = 123456;
718 assertExpectException(SecurityException.class,
719 /* messageRegex =*/ "Non-shell user attempted to call",
720 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
721
722 mContext.binder.callingUid = Process.SHELL_UID;
723 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
724
725 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
726 // Verify
727 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
728 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
729 null, DpmMockContext.CALLER_USER_HANDLE);
730 }
731
Makoto Onukib643fb02015-09-22 15:03:44 -0700732 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000733 * Test for: @{link DevicePolicyManager#setActivePasswordState}
734 *
735 * Validates that when the password for a user changes, the notification broadcast intent
736 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
737 * addition to ones in the original user.
738 */
739 public void testSetActivePasswordState_sendToProfiles() throws Exception {
740 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
741
742 final int MANAGED_PROFILE_USER_ID = 78;
743 final int MANAGED_PROFILE_ADMIN_UID =
744 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
745
746 // Setup device owner.
747 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
748 mContext.packageName = admin1.getPackageName();
749 setupDeviceOwner();
750
751 // Add a managed profile belonging to the system user.
752 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
753
754 // Change the parent user's password.
755 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
756
757 // Both the device owner and the managed profile owner should receive this broadcast.
758 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
759 intent.setComponent(admin1);
760 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
761
762 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
763 MockUtils.checkIntent(intent),
764 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
765 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
766 MockUtils.checkIntent(intent),
767 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
768 }
769
770 /**
771 * Test for: @{link DevicePolicyManager#setActivePasswordState}
772 *
773 * Validates that when the password for a managed profile changes, the notification broadcast
774 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
775 * its parent.
776 */
777 public void testSetActivePasswordState_notSentToParent() throws Exception {
778 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
779
780 final int MANAGED_PROFILE_USER_ID = 78;
781 final int MANAGED_PROFILE_ADMIN_UID =
782 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
783
784 // Setup device owner.
785 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
786 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100787 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000788 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
789 setupDeviceOwner();
790
791 // Add a managed profile belonging to the system user.
792 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
793
794 // Change the profile's password.
795 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
796
797 // Both the device owner and the managed profile owner should receive this broadcast.
798 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
799 intent.setComponent(admin1);
800 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
801
802 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
803 MockUtils.checkIntent(intent),
804 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
805 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
806 MockUtils.checkIntent(intent),
807 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
808 }
809 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000810 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700811 */
812 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000813 setDeviceOwner();
814
815 // Try to set a profile owner on the same user, which should fail.
816 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
817 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100818 assertExpectException(IllegalStateException.class,
819 /* messageRegex= */ "already has a device owner",
820 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000821
822 // DO admin can't be deactivated.
823 dpm.removeActiveAdmin(admin1);
824 assertTrue(dpm.isAdminActive(admin1));
825
826 // TODO Test getDeviceOwnerName() too. To do so, we need to change
827 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
828 }
829
830 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700831 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800832 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700833 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
834 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
835
Makoto Onukid932f762015-09-29 16:53:38 -0700836 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700837 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
838
Makoto Onukid932f762015-09-29 16:53:38 -0700839 // Make sure admin1 is installed on system user.
840 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700841
Makoto Onukic8a5a552015-11-19 14:29:12 -0800842 // Check various get APIs.
843 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
844
Makoto Onukib643fb02015-09-22 15:03:44 -0700845 // DO needs to be an DA.
846 dpm.setActiveAdmin(admin1, /* replace =*/ false);
847
848 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700849 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700850
Makoto Onukic8a5a552015-11-19 14:29:12 -0800851 // getDeviceOwnerComponent should return the admin1 component.
852 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
853 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
854
855 // Check various get APIs.
856 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
857
858 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
859 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
860 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
861 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
862
863 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
864
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000865 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100866 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000867 eq(admin1.getPackageName()));
868
Makoto Onukib643fb02015-09-22 15:03:44 -0700869 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100870 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 eq(UserHandle.USER_SYSTEM), eq(false));
872
873 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
874 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
875 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
876
Makoto Onukic8a5a552015-11-19 14:29:12 -0800877 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700878 }
879
Makoto Onukic8a5a552015-11-19 14:29:12 -0800880 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
881 final int origCallingUser = mContext.binder.callingUid;
882 final List origPermissions = new ArrayList(mContext.callerPermissions);
883 mContext.callerPermissions.clear();
884
885 mContext.callerPermissions.add(permission.MANAGE_USERS);
886
887 mContext.binder.callingUid = Process.SYSTEM_UID;
888
889 // TODO Test getDeviceOwnerName() too. To do so, we need to change
890 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
891 if (hasDeviceOwner) {
892 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
893 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
894 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
895
896 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
897 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
898 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
899 } else {
900 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
901 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
902 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
903
904 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
905 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
906 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
907 }
908
909 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
910 if (hasDeviceOwner) {
911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
912 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
913 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
914
915 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
916 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
917 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
918 } else {
919 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
920 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
921 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
922
923 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
924 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
925 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
926 }
927
928 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
929 // Still with MANAGE_USERS.
930 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
931 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
932 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
933
934 if (hasDeviceOwner) {
935 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
936 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
937 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
938 } else {
939 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
940 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
941 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
942 }
943
944 mContext.binder.callingUid = Process.SYSTEM_UID;
945 mContext.callerPermissions.remove(permission.MANAGE_USERS);
946 // System can still call "OnAnyUser" without MANAGE_USERS.
947 if (hasDeviceOwner) {
948 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
949 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
950 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
951
952 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
953 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
954 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
955 } else {
956 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
957 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
958 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
959
960 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
961 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
962 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
963 }
964
965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
966 // Still no MANAGE_USERS.
967 if (hasDeviceOwner) {
968 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
969 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
970 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
971 } else {
972 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
973 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
974 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
975 }
976
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100977 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
978 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
980 dpm::getDeviceOwnerComponentOnAnyUser);
981 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
982 dpm::getDeviceOwnerUserId);
983 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
984 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800985
986 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
987 // Still no MANAGE_USERS.
988 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
989 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
990 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
991
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100992 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
993 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
994 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
995 dpm::getDeviceOwnerComponentOnAnyUser);
996 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
997 dpm::getDeviceOwnerUserId);
998 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
999 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001000
1001 // Restore.
1002 mContext.binder.callingUid = origCallingUser;
1003 mContext.callerPermissions.addAll(origPermissions);
1004 }
1005
1006
Makoto Onukib643fb02015-09-22 15:03:44 -07001007 /**
1008 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1009 */
1010 public void testSetDeviceOwner_noSuchPackage() {
1011 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001012 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001013 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1014 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1015
1016 // Call from a process on the system user.
1017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1018
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001019 assertExpectException(IllegalArgumentException.class,
1020 /* messageRegex= */ "Invalid component",
1021 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001022 }
1023
1024 public void testSetDeviceOwner_failures() throws Exception {
1025 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1026 }
1027
Makoto Onukia52562c2015-10-01 16:12:31 -07001028 public void testClearDeviceOwner() throws Exception {
1029 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001030 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001031 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1032 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1033
1034 // Set admin1 as a DA to the secondary user.
1035 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1036
1037 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1038
1039 // Set admin 1 as the DO to the system user.
1040
1041 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1042 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1043 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1044 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1045
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001046 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001047 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001048 eq(admin1.getPackageName()));
1049
Makoto Onukic8a5a552015-11-19 14:29:12 -08001050 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001051
Makoto Onuki90b89652016-01-28 14:44:18 -08001052 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001053 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001054 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001055
1056 assertTrue(dpm.isAdminActive(admin1));
1057 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1058
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001060 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001061
1062 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001063 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1064 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001065
1066 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001067 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001068 assertExpectException(IllegalStateException.class,
1069 /* messageRegex= */ "User must be running and unlocked",
1070 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001071
Pavel Grafov75c0a892017-05-18 17:28:27 +01001072 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1073 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001074 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1075
1076 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001077 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001078
Pavel Grafov75c0a892017-05-18 17:28:27 +01001079 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001080 eq(false),
1081 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1082
Pavel Grafov75c0a892017-05-18 17:28:27 +01001083 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001084 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001085 eq(null),
1086 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001087
Sudheer Shanka101c3532018-01-08 16:28:42 -08001088 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1089 null, UserHandle.USER_SYSTEM);
1090
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001091 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001092
1093 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1094 // and once for clearing it.
1095 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1096 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1097 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001098 // TODO Check other calls.
1099 }
1100
1101 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1102 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001103 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001104 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1105 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1106
1107 // Set admin1 as a DA to the secondary user.
1108 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1109
1110 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1111
1112 // Set admin 1 as the DO to the system user.
1113
1114 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1115 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1116 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1117 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1118
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001119 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001120 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001121 eq(admin1.getPackageName()));
1122
Makoto Onukic8a5a552015-11-19 14:29:12 -08001123 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001124
1125 // Now call clear from the secondary user, which should throw.
1126 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1127
1128 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001129 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 eq(admin1.getPackageName()),
1131 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001132 assertExpectException(SecurityException.class,
1133 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1134 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001135
Makoto Onukic8a5a552015-11-19 14:29:12 -08001136 // DO shouldn't be removed.
1137 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001138 }
1139
Makoto Onukib643fb02015-09-22 15:03:44 -07001140 public void testSetProfileOwner() throws Exception {
1141 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001142
Makoto Onuki90b89652016-01-28 14:44:18 -08001143 // PO admin can't be deactivated.
1144 dpm.removeActiveAdmin(admin1);
1145 assertTrue(dpm.isAdminActive(admin1));
1146
Makoto Onuki803d6752015-10-30 12:58:39 -07001147 // Try setting DO on the same user, which should fail.
1148 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001149 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1150 runAsCaller(mServiceContext, dpms, dpm -> {
1151 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001152 assertExpectException(IllegalStateException.class,
1153 /* messageRegex= */ "already has a profile owner",
1154 () -> dpm.setDeviceOwner(admin2, "owner-name",
1155 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001156 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001157 }
1158
Makoto Onuki90b89652016-01-28 14:44:18 -08001159 public void testClearProfileOwner() throws Exception {
1160 setAsProfileOwner(admin1);
1161
1162 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1163
1164 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1165 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1166
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001167 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001168 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001169 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001170 assertExpectException(IllegalStateException.class,
1171 /* messageRegex= */ "User must be running and unlocked",
1172 () -> dpm.clearProfileOwner(admin1));
1173
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001174 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001175 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001176 dpm.clearProfileOwner(admin1);
1177
1178 // Check
1179 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001180 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001181 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1182 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001183 }
1184
Makoto Onukib643fb02015-09-22 15:03:44 -07001185 public void testSetProfileOwner_failures() throws Exception {
1186 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1187 }
1188
Makoto Onukia52562c2015-10-01 16:12:31 -07001189 public void testGetDeviceOwnerAdminLocked() throws Exception {
1190 checkDeviceOwnerWithMultipleDeviceAdmins();
1191 }
1192
1193 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1194 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1195 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1196 // make sure it gets the right component from the right user.
1197
1198 final int ANOTHER_USER_ID = 100;
1199 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1200
Pavel Grafov75c0a892017-05-18 17:28:27 +01001201 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001202
1203 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001204 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001205 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1206 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1207
1208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1209
Pavel Grafov75c0a892017-05-18 17:28:27 +01001210 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001211
Makoto Onukia52562c2015-10-01 16:12:31 -07001212 // Make sure the admin packge is installed to each user.
1213 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1214 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1215
1216 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1217 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1218
1219 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1220
1221
1222 // Set active admins to the users.
1223 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1224 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1225
1226 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1227 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1228
1229 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1230
1231 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001232 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001233 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1234
Makoto Onukic8a5a552015-11-19 14:29:12 -08001235 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001236
1237 // Then check getDeviceOwnerAdminLocked().
1238 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1239 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1240 }
1241
1242 /**
1243 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001244 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1245 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001246 *
1247 * We didn't use to persist the DO component class name, but now we do, and the above method
1248 * finds the right component from a package name upon migration.
1249 */
1250 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001251 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001252 checkDeviceOwnerWithMultipleDeviceAdmins();
1253
1254 // Overwrite the device owner setting and clears the clas name.
1255 dpms.mOwners.setDeviceOwner(
1256 new ComponentName(admin2.getPackageName(), ""),
1257 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1258 dpms.mOwners.writeDeviceOwner();
1259
1260 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001261 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001262
1263 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001264 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001265 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001266 initializeDpms();
1267
1268 // Now the DO component name is a full name.
1269 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1270 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001271 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001272 }
1273
Makoto Onukib643fb02015-09-22 15:03:44 -07001274 public void testSetGetApplicationRestriction() {
1275 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001276 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001277
1278 {
1279 Bundle rest = new Bundle();
1280 rest.putString("KEY_STRING", "Foo1");
1281 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1282 }
1283
1284 {
1285 Bundle rest = new Bundle();
1286 rest.putString("KEY_STRING", "Foo2");
1287 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1288 }
1289
1290 {
1291 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1292 assertNotNull(returned);
1293 assertEquals(returned.size(), 1);
1294 assertEquals(returned.get("KEY_STRING"), "Foo1");
1295 }
1296
1297 {
1298 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1299 assertNotNull(returned);
1300 assertEquals(returned.size(), 1);
1301 assertEquals(returned.get("KEY_STRING"), "Foo2");
1302 }
1303
1304 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1305 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1306 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001307
Edman Anjosf9946772016-11-28 16:35:15 +01001308 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001309 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1310 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001311 *
1312 * @param packageName the name of the package to be setup
1313 * @param appId the application ID to be given to the package
1314 * @return the UID of the package as known by the mock package manager
1315 */
1316 private int setupPackageInPackageManager(final String packageName, final int appId)
1317 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001318 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001319 ApplicationInfo.FLAG_HAS_CODE);
1320 }
1321
1322 /**
1323 * Setup a package in the package manager mock. Useful for faking installed applications.
1324 *
1325 * @param packageName the name of the package to be setup
1326 * @param userId the user id where the package will be "installed"
1327 * @param appId the application ID to be given to the package
1328 * @param flags flags to set in the ApplicationInfo for this package
1329 * @return the UID of the package as known by the mock package manager
1330 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001331 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1332 int flags) throws Exception {
1333 final int uid = UserHandle.getUid(userId, appId);
1334 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001335 final PackageInfo pi = new PackageInfo();
1336 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001337 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001338 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001339 eq(packageName),
1340 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001341 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001342 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001343 eq(packageName),
1344 anyInt(),
1345 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001346 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001347 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001348 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001349 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001350 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001351 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001352 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001353 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001354 return uid;
1355 }
1356
Robin Lee7f5c91c2017-02-08 21:27:02 +00001357 public void testCertificateDisclosure() throws Exception {
1358 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1359 final UserHandle user = UserHandle.of(userId);
1360
1361 mContext.applicationInfo = new ApplicationInfo();
1362 mContext.callerPermissions.add(permission.MANAGE_USERS);
1363 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001364 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001365 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1366
Robin Leeabaa0692017-02-20 20:54:22 +00001367 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1368 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001369
1370 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1371 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1372
1373 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001374 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001375 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001376 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001377 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001378 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001379 .cancelAsUser(anyString(), anyInt(), eq(user));
1380
1381 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001383 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001384 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1385 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001386 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001387 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001388 .notifyAsUser(anyString(), anyInt(), argThat(
1389 new BaseMatcher<Notification>() {
1390 @Override
1391 public boolean matches(Object item) {
1392 final Notification noti = (Notification) item;
1393 return TEST_STRING.equals(
1394 noti.extras.getString(Notification.EXTRA_TITLE));
1395 }
1396 @Override
1397 public void describeTo(Description description) {
1398 description.appendText(
1399 "Notification{title=\"" + TEST_STRING + "\"}");
1400 }
1401 }), eq(user));
1402 }
1403
Edman Anjosf9946772016-11-28 16:35:15 +01001404 /**
1405 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1406 * privileges can acually be exercised by a delegate are not covered here.
1407 */
1408 public void testDelegation() throws Exception {
1409 setAsProfileOwner(admin1);
1410
1411 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1412
1413 // Given two packages
1414 final String CERT_DELEGATE = "com.delegate.certs";
1415 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1416 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1417 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1418 20989);
1419
1420 // On delegation
1421 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1422 mContext.packageName = admin1.getPackageName();
1423 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1424 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1425
1426 // DPMS correctly stores and retrieves the delegates
1427 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1428 assertEquals(2, policy.mDelegationMap.size());
1429 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1430 DELEGATION_CERT_INSTALL);
1431 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1432 DELEGATION_CERT_INSTALL);
1433 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1434 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1435 DELEGATION_APP_RESTRICTIONS);
1436 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1437 DELEGATION_APP_RESTRICTIONS);
1438 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1439
1440 // On calling install certificate APIs from an unauthorized process
1441 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1442 mContext.packageName = RESTRICTIONS_DELEGATE;
1443
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001444 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1445 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001446
1447 // On calling install certificate APIs from an authorized process
1448 mContext.binder.callingUid = CERT_DELEGATE_UID;
1449 mContext.packageName = CERT_DELEGATE;
1450
1451 // DPMS executes without a SecurityException
1452 try {
1453 dpm.installCaCert(null, null);
1454 } catch (SecurityException unexpected) {
1455 fail("Threw SecurityException on authorized access");
1456 } catch (NullPointerException expected) {
1457 }
1458
1459 // On removing a delegate
1460 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1461 mContext.packageName = admin1.getPackageName();
1462 dpm.setCertInstallerPackage(admin1, null);
1463
1464 // DPMS does not allow access to ex-delegate
1465 mContext.binder.callingUid = CERT_DELEGATE_UID;
1466 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001467 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1468 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001469
1470 // But still allows access to other existing delegates
1471 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1472 mContext.packageName = RESTRICTIONS_DELEGATE;
1473 try {
1474 dpm.getApplicationRestrictions(null, "pkg");
1475 } catch (SecurityException expected) {
1476 fail("Threw SecurityException on authorized access");
1477 }
1478 }
1479
Esteban Talaverabf60f722015-12-10 16:26:44 +00001480 public void testApplicationRestrictionsManagingApp() throws Exception {
1481 setAsProfileOwner(admin1);
1482
Rubin Xued1928a2016-02-11 17:23:06 +00001483 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001484 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001485 final String nonDelegateExceptionMessageRegex =
1486 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001487 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001488 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1489 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001490
Esteban Talaverabf60f722015-12-10 16:26:44 +00001491 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1492 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001493 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1494 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001495 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001496 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001497 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001498 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1499 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001500
1501 // Check via the profile owner that no restrictions were set.
1502 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001503 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001504 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1505
Rubin Xued1928a2016-02-11 17:23:06 +00001506 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001507 assertExpectException(PackageManager.NameNotFoundException.class,
1508 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1509 () -> dpm.setApplicationRestrictionsManagingPackage(
1510 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001511
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 // Let appRestrictionsManagerPackage manage app restrictions
1513 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1514 assertEquals(appRestrictionsManagerPackage,
1515 dpm.getApplicationRestrictionsManagingPackage(admin1));
1516
1517 // Now that package should be able to set and retrieve app restrictions.
1518 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001519 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001520 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1521 dpm.setApplicationRestrictions(null, "pkg1", rest);
1522 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1523 assertEquals(1, returned.size(), 1);
1524 assertEquals("Foo1", returned.get("KEY_STRING"));
1525
1526 // The same app running on a separate user shouldn't be able to manage app restrictions.
1527 mContext.binder.callingUid = UserHandle.getUid(
1528 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1529 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001530 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1531 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532
1533 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1534 // too.
1535 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001536 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001537 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1538 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1539 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1540
1541 // Removing the ability for the package to manage app restrictions.
1542 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1543 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1544 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001545 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001546 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001547 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1548 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001549 }
1550
Makoto Onukia4f11972015-10-01 13:19:58 -07001551 public void testSetUserRestriction_asDo() throws Exception {
1552 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001553 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001554 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1555 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1556
1557 // First, set DO.
1558
1559 // Call from a process on the system user.
1560 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1561
1562 // Make sure admin1 is installed on system user.
1563 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001564
1565 // Call.
1566 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001567 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001568 UserHandle.USER_SYSTEM));
1569
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001570 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001571 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001572 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001573 DpmTestUtils.assertRestrictions(
1574 DpmTestUtils.newRestrictions(defaultRestrictions),
1575 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1576 );
1577 DpmTestUtils.assertRestrictions(
1578 DpmTestUtils.newRestrictions(defaultRestrictions),
1579 dpm.getUserRestrictions(admin1)
1580 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001581 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001582 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001583 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001584 eq(true) /* isDeviceOwner */,
1585 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001586 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001587 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001588
1589 for (String restriction : defaultRestrictions) {
1590 dpm.clearUserRestriction(admin1, restriction);
1591 }
1592
Esteban Talavera548a04b2016-12-20 15:22:30 +00001593 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001594 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595
1596 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001597 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001598 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001599 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1600 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001601 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001602
Makoto Onukia4f11972015-10-01 13:19:58 -07001603 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001604 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001605 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001606 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1607 UserManager.DISALLOW_ADD_USER),
1608 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001609 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001610
Makoto Onuki068c54a2015-10-13 14:34:03 -07001611 DpmTestUtils.assertRestrictions(
1612 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001613 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001614 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1615 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001616 DpmTestUtils.assertRestrictions(
1617 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001618 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001619 dpm.getUserRestrictions(admin1)
1620 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001621
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001622 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 eq(UserHandle.USER_SYSTEM),
1625 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001626 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001627 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001628
Makoto Onuki068c54a2015-10-13 14:34:03 -07001629 DpmTestUtils.assertRestrictions(
1630 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1631 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1632 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001633 DpmTestUtils.assertRestrictions(
1634 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1635 dpm.getUserRestrictions(admin1)
1636 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001637
1638 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001639 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 eq(UserHandle.USER_SYSTEM),
1641 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001642 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001643 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001644
Esteban Talavera548a04b2016-12-20 15:22:30 +00001645 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001646
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1648 // DO sets them, the scope is global.
1649 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001650 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001652 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001655 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1656 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658
1659 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1660 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001661 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662
1663 // More tests.
1664 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001665 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001667 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1668 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001669 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001670
1671 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001673 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 UserManager.DISALLOW_ADD_USER),
1676 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678
1679 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 eq(UserHandle.USER_SYSTEM),
1682 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 UserManager.DISALLOW_ADD_USER),
1685 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687
1688 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1689 // locally.
1690 dpm.setCameraDisabled(admin1, false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001691 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692
1693 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1694 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1695 dpm.setCameraDisabled(admin2, true);
1696
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001699 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 UserManager.DISALLOW_ADD_USER),
1702 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001704 // TODO Make sure restrictions are written to the file.
1705 }
1706
1707 public void testSetUserRestriction_asPo() {
1708 setAsProfileOwner(admin1);
1709
Makoto Onuki068c54a2015-10-13 14:34:03 -07001710 DpmTestUtils.assertRestrictions(
1711 DpmTestUtils.newRestrictions(),
1712 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1713 .ensureUserRestrictions()
1714 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001715
1716 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001717 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 eq(DpmMockContext.CALLER_USER_HANDLE),
1719 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001721 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722
Makoto Onukia4f11972015-10-01 13:19:58 -07001723 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 eq(DpmMockContext.CALLER_USER_HANDLE),
1726 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1727 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001729 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001730
Makoto Onuki068c54a2015-10-13 14:34:03 -07001731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(
1733 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1734 UserManager.DISALLOW_OUTGOING_CALLS
1735 ),
1736 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1737 .ensureUserRestrictions()
1738 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001739 DpmTestUtils.assertRestrictions(
1740 DpmTestUtils.newRestrictions(
1741 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1742 UserManager.DISALLOW_OUTGOING_CALLS
1743 ),
1744 dpm.getUserRestrictions(admin1)
1745 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001746
1747 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 eq(DpmMockContext.CALLER_USER_HANDLE),
1750 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001751 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001752 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001753
1754 DpmTestUtils.assertRestrictions(
1755 DpmTestUtils.newRestrictions(
1756 UserManager.DISALLOW_OUTGOING_CALLS
1757 ),
1758 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1759 .ensureUserRestrictions()
1760 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001761 DpmTestUtils.assertRestrictions(
1762 DpmTestUtils.newRestrictions(
1763 UserManager.DISALLOW_OUTGOING_CALLS
1764 ),
1765 dpm.getUserRestrictions(admin1)
1766 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001767
1768 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001770 eq(DpmMockContext.CALLER_USER_HANDLE),
1771 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001772 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001773 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001774
Makoto Onuki068c54a2015-10-13 14:34:03 -07001775 DpmTestUtils.assertRestrictions(
1776 DpmTestUtils.newRestrictions(),
1777 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1778 .ensureUserRestrictions()
1779 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001780 DpmTestUtils.assertRestrictions(
1781 DpmTestUtils.newRestrictions(),
1782 dpm.getUserRestrictions(admin1)
1783 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001784
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001785 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1786 // though when DO sets them they'll be applied globally.
1787 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001788 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001790 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001791 eq(DpmMockContext.CALLER_USER_HANDLE),
1792 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1793 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001794 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001795 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796
1797 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001798 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001800 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001801 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001802 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804
Makoto Onukia4f11972015-10-01 13:19:58 -07001805 // TODO Make sure restrictions are written to the file.
1806 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001807
Esteban Talavera548a04b2016-12-20 15:22:30 +00001808
1809 public void testDefaultEnabledUserRestrictions() throws Exception {
1810 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1811 mContext.callerPermissions.add(permission.MANAGE_USERS);
1812 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1813 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1814
1815 // First, set DO.
1816
1817 // Call from a process on the system user.
1818 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1819
1820 // Make sure admin1 is installed on system user.
1821 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1822
1823 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1824 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1825 UserHandle.USER_SYSTEM));
1826
1827 // Check that the user restrictions that are enabled by default are set. Then unset them.
1828 String[] defaultRestrictions = UserRestrictionsUtils
1829 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1830 assertTrue(defaultRestrictions.length > 0);
1831 DpmTestUtils.assertRestrictions(
1832 DpmTestUtils.newRestrictions(defaultRestrictions),
1833 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1834 );
1835 DpmTestUtils.assertRestrictions(
1836 DpmTestUtils.newRestrictions(defaultRestrictions),
1837 dpm.getUserRestrictions(admin1)
1838 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001839 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001840 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001841 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001842 eq(true) /* isDeviceOwner */,
1843 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001844 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001846
1847 for (String restriction : defaultRestrictions) {
1848 dpm.clearUserRestriction(admin1, restriction);
1849 }
1850
1851 assertNoDeviceOwnerRestrictions();
1852
1853 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001854 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001855 initializeDpms();
1856 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1857 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1858
1859 assertNoDeviceOwnerRestrictions();
1860
1861 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1862 // is set as it wasn't enabled during setDeviceOwner.
1863 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1864 assertFalse(UserRestrictionsUtils
1865 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1866 UserRestrictionsUtils
1867 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1868 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001869 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001870 initializeDpms();
1871 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1872 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1873
1874 DpmTestUtils.assertRestrictions(
1875 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1876 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1877 );
1878 DpmTestUtils.assertRestrictions(
1879 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1880 dpm.getUserRestrictions(admin1)
1881 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001884 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001885 eq(true) /* isDeviceOwner */,
1886 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001887 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001888 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001889
1890 // Remove the restriction.
1891 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1892
1893 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1894 initializeDpms();
1895 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1896 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1897 assertNoDeviceOwnerRestrictions();
1898 } finally {
1899 UserRestrictionsUtils
1900 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1901 }
1902 }
1903
1904 private void assertNoDeviceOwnerRestrictions() {
1905 DpmTestUtils.assertRestrictions(
1906 DpmTestUtils.newRestrictions(),
1907 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1908 );
1909 DpmTestUtils.assertRestrictions(
1910 DpmTestUtils.newRestrictions(),
1911 dpm.getUserRestrictions(admin1)
1912 );
1913 }
1914
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001915 public void testGetMacAddress() throws Exception {
1916 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1917 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1918 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1919
1920 // In this test, change the caller user to "system".
1921 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1922
1923 // Make sure admin1 is installed on system user.
1924 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1925
1926 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001927 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1928 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001929
1930 // DO needs to be an DA.
1931 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1932 assertTrue(dpm.isAdminActive(admin1));
1933
1934 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001935 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1936 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001937
1938 // Test 3. Caller has PO, but not DO.
1939 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001940 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1941 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001942
1943 // Remove PO.
1944 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001945 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001946 // Test 4, Caller is DO now.
1947 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1948
1949 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001950 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001951
1952 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001953 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001954 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001955
1956 // 4-3. With a real MAC address.
1957 final WifiInfo wi = new WifiInfo();
1958 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001959 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001960 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001961 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001962
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001963 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001964 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1965 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1966
1967 // In this test, change the caller user to "system".
1968 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1969
1970 // Make sure admin1 is installed on system user.
1971 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1972
1973 // Set admin1 as DA.
1974 dpm.setActiveAdmin(admin1, false);
1975 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001976 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1977 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001978
1979 // Set admin1 as PO.
1980 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001981 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1982 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001983
1984 // Remove PO and add DO.
1985 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001986 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001987 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1988
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001989 // admin1 is DO.
1990 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001991 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001992 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001993 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
1994 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001995
1996 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001997 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001998 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001999 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2000 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002001
2002 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002003 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002004 dpm.reboot(admin1);
2005 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002006
2007 public void testSetGetSupportText() {
2008 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2009 dpm.setActiveAdmin(admin1, true);
2010 dpm.setActiveAdmin(admin2, true);
2011 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2012
2013 // Null default support messages.
2014 {
2015 assertNull(dpm.getLongSupportMessage(admin1));
2016 assertNull(dpm.getShortSupportMessage(admin1));
2017 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2018 assertNull(dpm.getShortSupportMessageForUser(admin1,
2019 DpmMockContext.CALLER_USER_HANDLE));
2020 assertNull(dpm.getLongSupportMessageForUser(admin1,
2021 DpmMockContext.CALLER_USER_HANDLE));
2022 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2023 }
2024
2025 // Only system can call the per user versions.
2026 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002027 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2028 () -> dpm.getShortSupportMessageForUser(admin1,
2029 DpmMockContext.CALLER_USER_HANDLE));
2030 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2031 () -> dpm.getLongSupportMessageForUser(admin1,
2032 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002033 }
2034
2035 // Can't set message for admin in another uid.
2036 {
2037 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002038 assertExpectException(SecurityException.class,
2039 /* messageRegex= */ "is not owned by uid",
2040 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002041 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2042 }
2043
2044 // Set/Get short returns what it sets and other admins text isn't changed.
2045 {
2046 final String supportText = "Some text to test with.";
2047 dpm.setShortSupportMessage(admin1, supportText);
2048 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2049 assertNull(dpm.getLongSupportMessage(admin1));
2050 assertNull(dpm.getShortSupportMessage(admin2));
2051
2052 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2053 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2054 DpmMockContext.CALLER_USER_HANDLE));
2055 assertNull(dpm.getShortSupportMessageForUser(admin2,
2056 DpmMockContext.CALLER_USER_HANDLE));
2057 assertNull(dpm.getLongSupportMessageForUser(admin1,
2058 DpmMockContext.CALLER_USER_HANDLE));
2059 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2060
2061 dpm.setShortSupportMessage(admin1, null);
2062 assertNull(dpm.getShortSupportMessage(admin1));
2063 }
2064
2065 // Set/Get long returns what it sets and other admins text isn't changed.
2066 {
2067 final String supportText = "Some text to test with.\nWith more text.";
2068 dpm.setLongSupportMessage(admin1, supportText);
2069 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2070 assertNull(dpm.getShortSupportMessage(admin1));
2071 assertNull(dpm.getLongSupportMessage(admin2));
2072
2073 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2074 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 assertNull(dpm.getLongSupportMessageForUser(admin2,
2077 DpmMockContext.CALLER_USER_HANDLE));
2078 assertNull(dpm.getShortSupportMessageForUser(admin1,
2079 DpmMockContext.CALLER_USER_HANDLE));
2080 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2081
2082 dpm.setLongSupportMessage(admin1, null);
2083 assertNull(dpm.getLongSupportMessage(admin1));
2084 }
2085 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002086
phweiss73145f42017-01-17 19:06:38 +01002087 public void testCreateAdminSupportIntent() throws Exception {
2088 // Setup device owner.
2089 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2090 setupDeviceOwner();
2091
2092 // Nonexisting permission returns null
2093 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2094 assertNull(intent);
2095
2096 // Existing permission that is not set returns null
2097 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2098 assertNull(intent);
2099
2100 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002101 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002102 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2103 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2104 .thenReturn(true);
2105 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2106 assertNull(intent);
2107
2108 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002109 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002110 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2111 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2112 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2113 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2114 assertNotNull(intent);
2115 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2116 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2117 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002118 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002119 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2120 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2121
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002122 // Try with POLICY_DISABLE_CAMERA, POLICY_DISABLE_SCREEN_CAPTURE and
2123 // POLICY_MANDATORY_BACKUPS, which are not user restrictions
phweiss73145f42017-01-17 19:06:38 +01002124
2125 // Camera is not disabled
2126 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2127 assertNull(intent);
2128
2129 // Camera is disabled
2130 dpm.setCameraDisabled(admin1, true);
2131 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2132 assertNotNull(intent);
2133 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2134 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2135
2136 // Screen capture is not disabled
2137 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2138 assertNull(intent);
2139
2140 // Screen capture is disabled
2141 dpm.setScreenCaptureDisabled(admin1, true);
2142 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2143 assertNotNull(intent);
2144 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2145 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2146
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002147 // Backups are not mandatory
2148 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2149 assertNull(intent);
2150
2151 // Backups are mandatory
2152 ComponentName transportComponent = ComponentName.unflattenFromString(
2153 "android/com.android.internal.backup.LocalTransport");
2154 dpm.setMandatoryBackupTransport(admin1, transportComponent);
2155 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2156 assertNotNull(intent);
2157 assertEquals(DevicePolicyManager.POLICY_MANDATORY_BACKUPS,
2158 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2159
phweiss73145f42017-01-17 19:06:38 +01002160 // Same checks for different user
2161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2162 // Camera should be disabled by device owner
2163 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2164 assertNotNull(intent);
2165 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2166 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2167 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2168 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2169 // ScreenCapture should not be disabled by device owner
2170 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2171 assertNull(intent);
2172 }
2173
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002174 /**
2175 * Test for:
2176 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002177 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002178 * {@link DevicePolicyManager#isAffiliatedUser}
2179 */
2180 public void testUserAffiliation() throws Exception {
2181 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2182 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2183 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2184
2185 // Check that the system user is unaffiliated.
2186 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2187 assertFalse(dpm.isAffiliatedUser());
2188
2189 // Set a device owner on the system user. Check that the system user becomes affiliated.
2190 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2191 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2192 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2193 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002194 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002195
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002196 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002197 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2198 setAsProfileOwner(admin2);
2199 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002200 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002201
2202 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2203 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002204 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002205 userAffiliationIds.add("red");
2206 userAffiliationIds.add("green");
2207 userAffiliationIds.add("blue");
2208 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002209 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002210 assertFalse(dpm.isAffiliatedUser());
2211
2212 // Have the device owner specify a set of affiliation ids that do not intersect with those
2213 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002214 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002215 deviceAffiliationIds.add("cyan");
2216 deviceAffiliationIds.add("yellow");
2217 deviceAffiliationIds.add("magenta");
2218 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2219 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002220 MoreAsserts.assertContentsInAnyOrder(
2221 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002222 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2223 assertFalse(dpm.isAffiliatedUser());
2224
2225 // Have the profile owner specify a set of affiliation ids that intersect with those
2226 // specified by the device owner. Check that the test user becomes affiliated.
2227 userAffiliationIds.add("yellow");
2228 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002229 MoreAsserts.assertContentsInAnyOrder(
2230 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002231 assertTrue(dpm.isAffiliatedUser());
2232
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002233 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002234 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002235 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002236 assertFalse(dpm.isAffiliatedUser());
2237
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002238 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2239 dpm.setAffiliationIds(admin2, userAffiliationIds);
2240 assertTrue(dpm.isAffiliatedUser());
2241 dpm.clearProfileOwner(admin2);
2242 assertFalse(dpm.isAffiliatedUser());
2243
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002244 // Check that the system user remains affiliated.
2245 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2246 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002247
2248 // Clear the device owner - the user becomes unaffiliated.
2249 clearDeviceOwner();
2250 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002251 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002252
2253 public void testGetUserProvisioningState_defaultResult() {
2254 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2255 }
2256
2257 public void testSetUserProvisioningState_permission() throws Exception {
2258 setupProfileOwner();
2259 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2260
2261 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2262 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2263 }
2264
2265 public void testSetUserProvisioningState_unprivileged() throws Exception {
2266 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002267 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2268 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2269 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002270 }
2271
2272 public void testSetUserProvisioningState_noManagement() {
2273 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002274 assertExpectException(IllegalStateException.class,
2275 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2276 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2277 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002278 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2279 }
2280
2281 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2282 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2283 setupDeviceOwner();
2284 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2285
2286 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2287 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2288 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2289 }
2290
2291 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2292 throws Exception {
2293 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2294 setupDeviceOwner();
2295 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2296
2297 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2298 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2299 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2300 }
2301
2302 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2303 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2304 setupDeviceOwner();
2305 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2306
2307 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2308 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2309 }
2310
2311 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2312 throws Exception {
2313 setupProfileOwner();
2314 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2315
2316 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2317 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2318 DevicePolicyManager.STATE_USER_UNMANAGED);
2319 }
2320
2321 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2322 throws Exception {
2323 setupProfileOwner();
2324 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2325
2326 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2327 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2328 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2329 }
2330
2331 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2332 setupProfileOwner();
2333 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2334
2335 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2336 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2337 }
2338
2339 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2340 setupProfileOwner();
2341 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2342
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002343 assertExpectException(IllegalStateException.class,
2344 /* messageRegex= */ "Cannot move to user provisioning state",
2345 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2346 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2347 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002348 }
2349
2350 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2351 throws Exception {
2352 setupProfileOwner();
2353 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2354
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002355 assertExpectException(IllegalStateException.class,
2356 /* messageRegex= */ "Cannot move to user provisioning state",
2357 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2358 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2359 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002360 }
2361
2362 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2363 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2364 for (int state : states) {
2365 dpm.setUserProvisioningState(state, userId);
2366 assertEquals(state, dpm.getUserProvisioningState());
2367 }
2368 }
2369
2370 private void setupProfileOwner() throws Exception {
2371 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2372
2373 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2374 dpm.setActiveAdmin(admin1, false);
2375 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2376
2377 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2378 }
2379
2380 private void setupDeviceOwner() throws Exception {
2381 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2382
2383 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2384 dpm.setActiveAdmin(admin1, false);
2385 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2386
2387 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2388 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002389
2390 public void testSetMaximumTimeToLock() {
2391 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2392
2393 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2394 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2395
Pavel Grafov75c0a892017-05-18 17:28:27 +01002396 reset(getServices().powerManagerInternal);
2397 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002398
2399 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002400 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2401 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002402 reset(getServices().powerManagerInternal);
2403 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002404
2405 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002406 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2407 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002408 reset(getServices().powerManagerInternal);
2409 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002410
2411 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002412 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2413 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002414 reset(getServices().powerManagerInternal);
2415 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002416
2417 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002418 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2419 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002420 reset(getServices().powerManagerInternal);
2421 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002422
2423 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002424 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2425 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002426 reset(getServices().powerManagerInternal);
2427 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002428
2429 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002430 reset(getServices().powerManagerInternal);
2431 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002432
Pavel Grafov28939982017-10-03 15:11:52 +01002433 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2434 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2435 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002436 reset(getServices().powerManagerInternal);
2437 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002438
2439 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002440 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2441 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002442 reset(getServices().powerManagerInternal);
2443 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002444
Pavel Grafov28939982017-10-03 15:11:52 +01002445 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002446 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002447 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2448 verifyStayOnWhilePluggedCleared(false);
2449 }
2450
2451 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2452 // uses separate challenge.
2453 public void testSetMaximumTimeToLockProfile() throws Exception {
2454 final int PROFILE_USER = 15;
2455 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2456 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2457 mContext.binder.callingUid = PROFILE_ADMIN;
2458 final DevicePolicyManagerInternal dpmi =
2459 LocalServices.getService(DevicePolicyManagerInternal.class);
2460
2461 dpm.setMaximumTimeToLock(admin1, 0);
2462
2463 reset(getServices().powerManagerInternal);
2464 reset(getServices().settings);
2465
2466 // First add timeout for the profile.
2467 dpm.setMaximumTimeToLock(admin1, 10);
2468 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2469
2470 reset(getServices().powerManagerInternal);
2471 reset(getServices().settings);
2472
2473 // Add separate challenge
2474 when(getServices().lockPatternUtils
2475 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2476 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2477
2478 verifyScreenTimeoutCall(10L, PROFILE_USER);
2479 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2480
2481 reset(getServices().powerManagerInternal);
2482 reset(getServices().settings);
2483
2484 // Remove the timeout.
2485 dpm.setMaximumTimeToLock(admin1, 0);
2486 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2487 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2488
2489 reset(getServices().powerManagerInternal);
2490 reset(getServices().settings);
2491
2492 // Add it back.
2493 dpm.setMaximumTimeToLock(admin1, 10);
2494 verifyScreenTimeoutCall(10L, PROFILE_USER);
2495 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2496
2497 reset(getServices().powerManagerInternal);
2498 reset(getServices().settings);
2499
2500 // Remove separate challenge.
2501 reset(getServices().lockPatternUtils);
2502 when(getServices().lockPatternUtils
2503 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2504 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2505
2506 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2507 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2508
2509 reset(getServices().powerManagerInternal);
2510 reset(getServices().settings);
2511
2512 // Remove the timeout.
2513 dpm.setMaximumTimeToLock(admin1, 0);
2514 verifyScreenTimeoutCall(null, PROFILE_USER);
2515 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002516 }
2517
Michal Karpinski943aabd2016-10-06 11:09:25 +01002518 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2519 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2520 setupDeviceOwner();
2521 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2522
Michal Karpinskid084ca52017-01-18 15:54:18 +00002523 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2524 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2525 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2526 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2527 - ONE_MINUTE;
2528
2529 // verify that the minimum timeout cannot be modified on user builds (system property is
2530 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002531 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002532
2533 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2534 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2535 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2536
Pavel Grafov75c0a892017-05-18 17:28:27 +01002537 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002538
2539 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002540 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002541
Michal Karpinskid084ca52017-01-18 15:54:18 +00002542 // reset to default (0 means the admin is not participating, so default should be returned)
2543 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002544
2545 // aggregation should be the default if unset by any admin
2546 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2547 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2548
2549 // admin not participating by default
2550 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2551
2552 //clamping from the top
2553 dpm.setRequiredStrongAuthTimeout(admin1,
2554 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2555 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2556 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2557 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2558 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2559
Michal Karpinskid084ca52017-01-18 15:54:18 +00002560 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002561 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2562 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2563 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2564 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2565
2566 // clamping from the bottom
2567 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2568 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2569 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2570
Michal Karpinskid084ca52017-01-18 15:54:18 +00002571 // values within range
2572 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2573 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2574 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2575
2576 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2577 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2578 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002579
2580 // reset to default
2581 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2582 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2583 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2584 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2585
2586 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002587 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2588 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002589 }
2590
Pavel Grafov28939982017-10-03 15:11:52 +01002591 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002592 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002593 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002594 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002595 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002596 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002597 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002598 }
Pavel Grafov28939982017-10-03 15:11:52 +01002599 }
2600
2601 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002602 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2603 // UnfinishedVerificationException.
2604 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002605
Esteban Talavera01576862016-12-15 11:16:44 +00002606 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002607 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002608 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002609 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002610 .thenReturn(false);
2611 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002612 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2613 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002614 .thenReturn(true);
2615 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2616
2617 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002618 }
Victor Chang3e794af2016-03-04 13:48:17 +00002619
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002620 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2621 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002622 mContext.packageName = admin1.getPackageName();
2623 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002624 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2625 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2626 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2627 false);
2628 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2629 }
2630
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002631 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2632 setup_DeviceAdminFeatureOff();
2633 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2635 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2636 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2637 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2638 assertCheckProvisioningPreCondition(
2639 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2640 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2641 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2642 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2643 }
2644
Esteban Talavera01576862016-12-15 11:16:44 +00002645 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002646 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002647 .thenReturn(false);
2648 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002649 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2650 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002651 .thenReturn(true);
2652 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2653
2654 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002655 }
Victor Chang3e794af2016-03-04 13:48:17 +00002656
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002657 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2658 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002659 mContext.packageName = admin1.getPackageName();
2660 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002661 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2662 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2663 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2664 false);
2665 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2666
2667 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002668 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002669 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2670 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2671 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2672 true);
2673 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2674 }
2675
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002676 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2677 setup_ManagedProfileFeatureOff();
2678 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2679 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2680 DevicePolicyManager.CODE_OK);
2681 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2682 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2683 assertCheckProvisioningPreCondition(
2684 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2685 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2686 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2687 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2688
2689 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002690 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002691 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2692 DevicePolicyManager.CODE_OK);
2693 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2694 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2695 assertCheckProvisioningPreCondition(
2696 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2697 DevicePolicyManager.CODE_OK);
2698 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2699 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2700 }
2701
Esteban Talavera01576862016-12-15 11:16:44 +00002702 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002703 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002704 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002705 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2706 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002707 .thenReturn(true);
2708 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2709
2710 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002711 }
Victor Chang3e794af2016-03-04 13:48:17 +00002712
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002713 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2714 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002715 mContext.packageName = admin1.getPackageName();
2716 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002717 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2718 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2719 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2720 false /* because of non-split user */);
2721 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2722 false /* because of non-split user */);
2723 }
2724
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002725 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002726 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002727 setup_nonSplitUser_firstBoot_primaryUser();
2728 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2729 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2730 DevicePolicyManager.CODE_OK);
2731 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2732 DevicePolicyManager.CODE_OK);
2733 assertCheckProvisioningPreCondition(
2734 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2735 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2736 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2737 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2738 }
2739
Esteban Talavera01576862016-12-15 11:16:44 +00002740 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002741 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002742 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002743 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2744 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002745 .thenReturn(true);
2746 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2747
2748 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002749 }
Victor Chang3e794af2016-03-04 13:48:17 +00002750
Nicolas Prevot45d29072017-01-18 16:11:19 +00002751 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2752 setDeviceOwner();
2753 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2754 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2755 }
2756
2757 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2758 setup_nonSplitUser_withDo_primaryUser();
2759 final int MANAGED_PROFILE_USER_ID = 18;
2760 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2761 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002762 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002763 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002764 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002765 true)).thenReturn(true);
2766 }
2767
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002768 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2769 throws Exception {
2770 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002771 mContext.packageName = admin1.getPackageName();
2772 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002773 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2774 false/* because of completed device setup */);
2775 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2776 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2777 false/* because of non-split user */);
2778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2779 false/* because of non-split user */);
2780 }
2781
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002782 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2783 throws Exception {
2784 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2785 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2786 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2787 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2788 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2789 DevicePolicyManager.CODE_OK);
2790 assertCheckProvisioningPreCondition(
2791 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2792 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2794 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2795 }
2796
Nicolas Prevot45d29072017-01-18 16:11:19 +00002797 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2798 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002799 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002800 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2801
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2803 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002804 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002805
2806 // COMP mode is allowed.
2807 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2808 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002809 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002810
Nicolas Prevot45d29072017-01-18 16:11:19 +00002811 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002812 assertCheckProvisioningPreCondition(
2813 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002814 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002815 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002816 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2817 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2818 }
Esteban Talavera01576862016-12-15 11:16:44 +00002819
Nicolas Prevot45d29072017-01-18 16:11:19 +00002820 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2821 setup_nonSplitUser_withDo_primaryUser();
2822 mContext.packageName = admin1.getPackageName();
2823 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2824 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2825 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002826 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002827 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2828 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2829 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002830 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002831 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2832 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2833 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2834 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2835 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002836 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002837 assertCheckProvisioningPreCondition(
2838 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002839 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002840 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2842 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2843 }
Esteban Talavera01576862016-12-15 11:16:44 +00002844
Nicolas Prevot45d29072017-01-18 16:11:19 +00002845 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2846 throws Exception {
2847 setup_nonSplitUser_withDo_primaryUser();
2848 mContext.packageName = admin1.getPackageName();
2849 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002850 // The DO should not be allowed to initiate provisioning if the restriction is set by
2851 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002852 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002853 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2854 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2855 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002856 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002857 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2858 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2859 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2860 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2861 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2863
2864 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002865 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002866 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002867 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002868 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2869 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2870 }
2871
2872 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2873 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2874 mContext.packageName = admin1.getPackageName();
2875 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2876
2877 // We can delete the managed profile to create a new one, so provisioning is allowed.
2878 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2879 DevicePolicyManager.CODE_OK);
2880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2881 assertCheckProvisioningPreCondition(
2882 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2883 DpmMockContext.ANOTHER_PACKAGE_NAME,
2884 DevicePolicyManager.CODE_OK);
2885 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2886 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2887 }
2888
2889 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2890 throws Exception {
2891 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2892 mContext.packageName = admin1.getPackageName();
2893 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002894 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002895 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2896 eq(UserHandle.SYSTEM)))
2897 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002898 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002899 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2900 eq(UserHandle.SYSTEM)))
2901 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002902
2903 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002904 assertCheckProvisioningPreCondition(
2905 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2906 DpmMockContext.ANOTHER_PACKAGE_NAME,
2907 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2909 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002910
2911 // But the device owner can still do it because it has set the restriction itself.
2912 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2913 DevicePolicyManager.CODE_OK);
2914 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002915 }
2916
2917 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002918 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002919 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002920 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2921 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002922 .thenReturn(false);
2923 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2924
2925 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002926 }
Victor Chang3e794af2016-03-04 13:48:17 +00002927
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2929 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002930 mContext.packageName = admin1.getPackageName();
2931 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002932 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2933 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2934 false /* because canAddMoreManagedProfiles returns false */);
2935 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2936 true);
2937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2938 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002939 }
2940
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002941 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2942 throws Exception {
2943 setup_splitUser_firstBoot_systemUser();
2944 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2945 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2946 DevicePolicyManager.CODE_OK);
2947 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002948 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002949 assertCheckProvisioningPreCondition(
2950 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2951 DevicePolicyManager.CODE_OK);
2952 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2953 DevicePolicyManager.CODE_SYSTEM_USER);
2954 }
2955
Esteban Talavera01576862016-12-15 11:16:44 +00002956 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002957 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002958 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002959 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
2960 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002961 .thenReturn(false);
2962 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2963
2964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002965 }
Victor Chang3e794af2016-03-04 13:48:17 +00002966
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2968 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002969 mContext.packageName = admin1.getPackageName();
2970 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002971 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2972 true/* it's undefined behavior. Can be changed into false in the future */);
2973 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2974 false /* because canAddMoreManagedProfiles returns false */);
2975 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2976 true/* it's undefined behavior. Can be changed into false in the future */);
2977 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2978 false/* because calling uid is system user */);
2979 }
2980
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002981 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2982 throws Exception {
2983 setup_splitUser_afterDeviceSetup_systemUser();
2984 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2985 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2986 DevicePolicyManager.CODE_OK);
2987 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002988 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002989 assertCheckProvisioningPreCondition(
2990 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2991 DevicePolicyManager.CODE_OK);
2992 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2993 DevicePolicyManager.CODE_SYSTEM_USER);
2994 }
2995
Esteban Talavera01576862016-12-15 11:16:44 +00002996 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002997 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002998 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002999 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3000 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003001 true)).thenReturn(true);
3002 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3003
3004 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003005 }
Victor Chang3e794af2016-03-04 13:48:17 +00003006
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003007 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3008 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003009 mContext.packageName = admin1.getPackageName();
3010 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003011 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3012 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3013 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3014 true);
3015 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003016 }
3017
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003018 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003019 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003020 setup_splitUser_firstBoot_primaryUser();
3021 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3022 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3023 DevicePolicyManager.CODE_OK);
3024 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3025 DevicePolicyManager.CODE_OK);
3026 assertCheckProvisioningPreCondition(
3027 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3028 DevicePolicyManager.CODE_OK);
3029 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3030 DevicePolicyManager.CODE_OK);
3031 }
3032
Esteban Talavera01576862016-12-15 11:16:44 +00003033 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003034 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003035 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3037 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003038 true)).thenReturn(true);
3039 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3040
3041 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 }
Victor Chang3e794af2016-03-04 13:48:17 +00003043
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003044 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3045 throws Exception {
3046 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003047 mContext.packageName = admin1.getPackageName();
3048 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3050 true/* it's undefined behavior. Can be changed into false in the future */);
3051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3053 true/* it's undefined behavior. Can be changed into false in the future */);
3054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3055 false/* because user setup completed */);
3056 }
3057
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003058 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003059 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003060 setup_splitUser_afterDeviceSetup_primaryUser();
3061 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3062 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3063 DevicePolicyManager.CODE_OK);
3064 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3065 DevicePolicyManager.CODE_OK);
3066 assertCheckProvisioningPreCondition(
3067 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3068 DevicePolicyManager.CODE_OK);
3069 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3070 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3071 }
3072
Esteban Talavera01576862016-12-15 11:16:44 +00003073 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003074 setDeviceOwner();
3075
Pavel Grafov75c0a892017-05-18 17:28:27 +01003076 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003077 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003078 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3079 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003080 .thenReturn(false);
3081 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3082
3083 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 }
Victor Chang3e794af2016-03-04 13:48:17 +00003085
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003086 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3087 throws Exception {
3088 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003089 mContext.packageName = admin1.getPackageName();
3090 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3092 false /* can't provision managed profile on system user */);
3093 }
3094
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003095 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003096 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003097 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3098 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3099 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3100 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3101 }
3102
3103 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003104 setDeviceOwner();
3105
Pavel Grafov75c0a892017-05-18 17:28:27 +01003106 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003107 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003108 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3109 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003110 true)).thenReturn(true);
3111 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3112
3113 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003114 }
Victor Chang3e794af2016-03-04 13:48:17 +00003115
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003116 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3117 throws Exception {
3118 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003119 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3120 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003121 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3122 }
3123
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003124 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003125 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003126 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3127 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003128
3129 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003130 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3131 DevicePolicyManager.CODE_OK);
3132 }
3133
3134 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003135 setDeviceOwner();
3136
Pavel Grafov75c0a892017-05-18 17:28:27 +01003137 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003138 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003139 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3140 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003141 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3142 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003143 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003144 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003145 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003146 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003147 true)).thenReturn(true);
3148 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3149
3150 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003151 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003152
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003153 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3154 throws Exception {
3155 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003156 mContext.packageName = admin1.getPackageName();
3157 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003158 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3159 }
3160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3162 throws Exception {
3163 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3165 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3166 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3167 }
3168
3169 public void testCheckProvisioningPreCondition_permission() {
3170 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003171 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3172 () -> dpm.checkProvisioningPreCondition(
3173 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003174 }
3175
Victor Chang3577ed22016-08-25 18:49:26 +01003176 public void testForceUpdateUserSetupComplete_permission() {
3177 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003178 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3179 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003180 }
3181
3182 public void testForceUpdateUserSetupComplete_systemUser() {
3183 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3184 // GIVEN calling from user 20
3185 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003186 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3187 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003188 }
3189
3190 public void testForceUpdateUserSetupComplete_userbuild() {
3191 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3192 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3193
3194 final int userId = UserHandle.USER_SYSTEM;
3195 // GIVEN userComplete is false in SettingsProvider
3196 setUserSetupCompleteForUser(false, userId);
3197
3198 // GIVEN userComplete is true in DPM
3199 DevicePolicyManagerService.DevicePolicyData userData =
3200 new DevicePolicyManagerService.DevicePolicyData(userId);
3201 userData.mUserSetupComplete = true;
3202 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3203
3204 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003205 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003206
3207 assertTrue(dpms.hasUserSetupCompleted());
3208
3209 dpm.forceUpdateUserSetupComplete();
3210
3211 // THEN the state in dpms is not changed
3212 assertTrue(dpms.hasUserSetupCompleted());
3213 }
3214
3215 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3216 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3217 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3218
3219 final int userId = UserHandle.USER_SYSTEM;
3220 // GIVEN userComplete is false in SettingsProvider
3221 setUserSetupCompleteForUser(false, userId);
3222
3223 // GIVEN userComplete is true in DPM
3224 DevicePolicyManagerService.DevicePolicyData userData =
3225 new DevicePolicyManagerService.DevicePolicyData(userId);
3226 userData.mUserSetupComplete = true;
3227 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3228
3229 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003230 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003231
3232 assertTrue(dpms.hasUserSetupCompleted());
3233
3234 dpm.forceUpdateUserSetupComplete();
3235
3236 // THEN the state in dpms is not changed
3237 assertFalse(dpms.hasUserSetupCompleted());
3238 }
3239
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003240 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003241 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003242 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003243
3244 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3245 runAsCaller(mAdmin1Context, dpms, dpm -> {
3246 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3247 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003248 }
3249
3250 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3251 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3252 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003253
3254 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3255 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003256 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003257 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3258 .thenReturn(true);
3259
3260 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003261 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003262
3263 // Enabling logging should not change the timestamp.
3264 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003265 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003266 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003267 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003268 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003269 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003270
3271 // Retrieving the logs should update the timestamp.
3272 final long beforeRetrieval = System.currentTimeMillis();
3273 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003274 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003275 final long afterRetrieval = System.currentTimeMillis();
3276 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3277 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3278
3279 // Retrieving the pre-boot logs should update the timestamp.
3280 Thread.sleep(2);
3281 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003282 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003283 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3284
3285 // Checking the timestamp again should not change it.
3286 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003287 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003288
3289 // Retrieving the logs again should update the timestamp.
3290 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003291 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003292 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3293
3294 // Disabling logging should not change the timestamp.
3295 Thread.sleep(2);
3296 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003297 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003298
3299 // Restarting the DPMS should not lose the timestamp.
3300 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003301 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003302
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003303 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3304 mContext.binder.callingUid = 1234567;
3305 mContext.callerPermissions.add(permission.MANAGE_USERS);
3306 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3307 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3308
3309 // System can retrieve the timestamp.
3310 mContext.binder.clearCallingIdentity();
3311 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3312
3313 // Removing the device owner should clear the timestamp.
3314 clearDeviceOwner();
3315 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003316 }
3317
yuemingw0de748d2017-11-15 19:22:27 +00003318 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3319 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3320 setupDeviceOwner();
3321 assertExpectException(SecurityException.class, null, () ->
3322 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3323 }
3324
3325 public void testSetSystemSettingFailWithPO() throws Exception {
3326 setupProfileOwner();
3327 assertExpectException(SecurityException.class, null, () ->
3328 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0"));
3329 }
3330
3331 public void testSetSystemSetting() throws Exception {
3332 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3333 setupDeviceOwner();
3334 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3335 verify(getServices().settings).settingsSystemPutString(
3336 Settings.System.SCREEN_BRIGHTNESS, "0");
3337 }
3338
yuemingwe43cdf72017-10-12 16:52:11 +01003339 public void testSetTime() throws Exception {
3340 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3341 setupDeviceOwner();
3342 dpm.setTime(admin1, 0);
3343 verify(getServices().alarmManager).setTime(0);
3344 }
3345
3346 public void testSetTimeFailWithPO() throws Exception {
3347 setupProfileOwner();
3348 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3349 }
3350
3351 public void testSetTimeWithAutoTimeOn() throws Exception {
3352 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3353 setupDeviceOwner();
3354 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3355 .thenReturn(1);
3356 assertFalse(dpm.setTime(admin1, 0));
3357 }
3358
3359 public void testSetTimeZone() throws Exception {
3360 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3361 setupDeviceOwner();
3362 dpm.setTimeZone(admin1, "Asia/Shanghai");
3363 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3364 }
3365
3366 public void testSetTimeZoneFailWithPO() throws Exception {
3367 setupProfileOwner();
3368 assertExpectException(SecurityException.class, null,
3369 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3370 }
3371
3372 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3373 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3374 setupDeviceOwner();
3375 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3376 .thenReturn(1);
3377 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3378 }
3379
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003380 public void testGetLastBugReportRequestTime() throws Exception {
3381 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3382 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003383
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003384 mContext.packageName = admin1.getPackageName();
3385 mContext.applicationInfo = new ApplicationInfo();
3386 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3387 .thenReturn(Color.WHITE);
3388 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3389 anyObject())).thenReturn(Color.WHITE);
3390
Esteban Talaverad36dd152016-12-15 08:51:45 +00003391 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3392 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003393 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003394
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003396 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003397
3398 // Requesting a bug report should update the timestamp.
3399 final long beforeRequest = System.currentTimeMillis();
3400 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003401 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003402 final long afterRequest = System.currentTimeMillis();
3403 assertTrue(bugReportRequestTime >= beforeRequest);
3404 assertTrue(bugReportRequestTime <= afterRequest);
3405
3406 // Checking the timestamp again should not change it.
3407 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003408 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003409
3410 // Restarting the DPMS should not lose the timestamp.
3411 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003412 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003413
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003414 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3415 mContext.binder.callingUid = 1234567;
3416 mContext.callerPermissions.add(permission.MANAGE_USERS);
3417 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3418 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3419
3420 // System can retrieve the timestamp.
3421 mContext.binder.clearCallingIdentity();
3422 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3423
3424 // Removing the device owner should clear the timestamp.
3425 clearDeviceOwner();
3426 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003427 }
3428
3429 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3430 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3431 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003432 mContext.packageName = admin1.getPackageName();
3433 mContext.applicationInfo = new ApplicationInfo();
3434 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3435 .thenReturn(Color.WHITE);
3436 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3437 anyObject())).thenReturn(Color.WHITE);
3438
3439 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3440 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003441 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003442 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003443 .thenReturn(true);
3444
3445 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003446 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003447
3448 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3449 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003450 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003451
3452 // Enabling logging should not change the timestamp.
3453 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003454 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003455
3456 // Retrieving the logs should update the timestamp.
3457 final long beforeRetrieval = System.currentTimeMillis();
3458 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003459 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003460 final long afterRetrieval = System.currentTimeMillis();
3461 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3462 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3463
3464 // Checking the timestamp again should not change it.
3465 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003466 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003467
3468 // Retrieving the logs again should update the timestamp.
3469 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003470 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003471 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3472
3473 // Disabling logging should not change the timestamp.
3474 Thread.sleep(2);
3475 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003476 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003477
3478 // Restarting the DPMS should not lose the timestamp.
3479 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003480 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3481
3482 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3483 mContext.binder.callingUid = 1234567;
3484 mContext.callerPermissions.add(permission.MANAGE_USERS);
3485 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3486 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3487
3488 // System can retrieve the timestamp.
3489 mContext.binder.clearCallingIdentity();
3490 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3491
3492 // Removing the device owner should clear the timestamp.
3493 clearDeviceOwner();
3494 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003495 }
3496
Tony Mak2f26b792016-11-28 17:54:51 +00003497 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3498 // Setup device owner.
3499 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3500 setupDeviceOwner();
3501
3502 // Only device owner is setup, the result list should be empty.
3503 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3504 MoreAsserts.assertEmpty(targetUsers);
3505
3506 // Setup a managed profile managed by the same admin.
3507 final int MANAGED_PROFILE_USER_ID = 15;
3508 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3509 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3510
3511 // Add a secondary user, it should never talk with.
3512 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003513 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003514
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003515 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3516 // other.
3517 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3518 MoreAsserts.assertEmpty(targetUsers);
3519
3520 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3521 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3522 MoreAsserts.assertEmpty(targetUsers);
3523
3524 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003525 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003526 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3527 dpm.setAffiliationIds(admin1, userAffiliationIds);
3528
3529 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3530 dpm.setAffiliationIds(admin1, userAffiliationIds);
3531
Tony Mak2f26b792016-11-28 17:54:51 +00003532 // Calling from device owner admin, the result list should just contain the managed
3533 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003534 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003535 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3536 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3537
3538 // Calling from managed profile admin, the result list should just contain the system
3539 // user id.
3540 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3541 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3542 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003543
3544 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003545 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003546
3547 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3548 // to each other.
3549 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3550 MoreAsserts.assertEmpty(targetUsers);
3551
3552 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3553 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3554 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003555 }
3556
3557 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3558 // Setup a device owner.
3559 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3560 setupDeviceOwner();
3561
3562 // Set up a managed profile managed by different package.
3563 final int MANAGED_PROFILE_USER_ID = 15;
3564 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3565 final ComponentName adminDifferentPackage =
3566 new ComponentName("another.package", "whatever.class");
3567 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3568
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003569 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003570 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003571 dpm.setAffiliationIds(admin1, userAffiliationIds);
3572
3573 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3574 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3575
Tony Mak2f26b792016-11-28 17:54:51 +00003576 // Calling from device owner admin, we should get zero bind device admin target users as
3577 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003578 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003579 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3580 MoreAsserts.assertEmpty(targetUsers);
3581
3582 // Calling from managed profile admin, we should still get zero target users for the same
3583 // reason.
3584 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3585 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3586 MoreAsserts.assertEmpty(targetUsers);
3587 }
3588
Charles Hee078db72017-10-19 18:03:20 +01003589 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003590 // Setup a device owner.
3591 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3592 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003593 // Lock task policy is updated when loading user data.
3594 verify(getServices().iactivityManager).updateLockTaskPackages(
3595 UserHandle.USER_SYSTEM, new String[0]);
3596 verify(getServices().iactivityManager).updateLockTaskFeatures(
3597 UserHandle.USER_SYSTEM, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003598
3599 // Set up a managed profile managed by different package (package name shouldn't matter)
3600 final int MANAGED_PROFILE_USER_ID = 15;
3601 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3602 final ComponentName adminDifferentPackage =
3603 new ComponentName("another.package", "whatever.class");
3604 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Charles Hee078db72017-10-19 18:03:20 +01003605 verify(getServices().iactivityManager).updateLockTaskPackages(
3606 MANAGED_PROFILE_USER_ID, new String[0]);
3607 verify(getServices().iactivityManager).updateLockTaskFeatures(
3608 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003609
3610 // The DO can still set lock task packages
3611 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3612 final String[] doPackages = {"doPackage1", "doPackage2"};
3613 dpm.setLockTaskPackages(admin1, doPackages);
3614 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3615 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3616 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
Charles Hee078db72017-10-19 18:03:20 +01003617 verify(getServices().iactivityManager).updateLockTaskPackages(
3618 UserHandle.USER_SYSTEM, doPackages);
3619 // And the DO can still set lock task features
3620 final int doFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3621 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3622 dpm.setLockTaskFeatures(admin1, doFlags);
3623 verify(getServices().iactivityManager).updateLockTaskFeatures(
3624 UserHandle.USER_SYSTEM, doFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003625
3626 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3627 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3628 final String[] poPackages = {"poPackage1", "poPackage2"};
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003629 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3630 () -> dpm.setLockTaskPackages(adminDifferentPackage, poPackages));
3631 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3632 () -> dpm.getLockTaskPackages(adminDifferentPackage));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003633 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
Charles Hee078db72017-10-19 18:03:20 +01003634 // And it shouldn't be able to setLockTaskFeatures.
3635 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3636 | DevicePolicyManager.LOCK_TASK_FEATURE_RECENTS;
3637 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3638 () -> dpm.setLockTaskFeatures(adminDifferentPackage, poFlags));
Esteban Talaverabdcada92017-02-01 14:20:06 +00003639
3640 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003641 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003642 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3643 dpm.setAffiliationIds(admin1, userAffiliationIds);
3644
3645 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3646 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3647
3648 // Now the managed profile can set lock task packages.
3649 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3650 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3651 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3652 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003653 verify(getServices().iactivityManager).updateLockTaskPackages(
3654 MANAGED_PROFILE_USER_ID, poPackages);
3655 // And it can set lock task features.
3656 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
3657 verify(getServices().iactivityManager).updateLockTaskFeatures(
3658 MANAGED_PROFILE_USER_ID, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003659
3660 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003661 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003662 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3663 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003664 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3665 MANAGED_PROFILE_USER_ID, new String[0]);
3666 verify(getServices().iactivityManager, times(2)).updateLockTaskFeatures(
3667 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003668
3669 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3670 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3671 }
3672
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003673 public void testIsDeviceManaged() throws Exception {
3674 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3675 setupDeviceOwner();
3676
3677 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3678 // find out that the device has a device owner.
3679 assertTrue(dpm.isDeviceManaged());
3680 mContext.binder.callingUid = 1234567;
3681 mContext.callerPermissions.add(permission.MANAGE_USERS);
3682 assertTrue(dpm.isDeviceManaged());
3683 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3684 mContext.binder.clearCallingIdentity();
3685 assertTrue(dpm.isDeviceManaged());
3686
3687 clearDeviceOwner();
3688
3689 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3690 // not have a device owner.
3691 mContext.binder.callingUid = 1234567;
3692 mContext.callerPermissions.add(permission.MANAGE_USERS);
3693 assertFalse(dpm.isDeviceManaged());
3694 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3695 mContext.binder.clearCallingIdentity();
3696 assertFalse(dpm.isDeviceManaged());
3697 }
3698
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003699 public void testDeviceOwnerOrganizationName() throws Exception {
3700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3701 setupDeviceOwner();
3702
3703 dpm.setOrganizationName(admin1, "organization");
3704
3705 // Device owner can retrieve organization managing the device.
3706 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3707
3708 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3709 mContext.binder.callingUid = 1234567;
3710 mContext.callerPermissions.add(permission.MANAGE_USERS);
3711 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3712 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3713
3714 // System can retrieve organization managing the device.
3715 mContext.binder.clearCallingIdentity();
3716 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3717
3718 // Removing the device owner clears the organization managing the device.
3719 clearDeviceOwner();
3720 assertNull(dpm.getDeviceOwnerOrganizationName());
3721 }
3722
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003723 public void testWipeDataManagedProfile() throws Exception {
3724 final int MANAGED_PROFILE_USER_ID = 15;
3725 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3726 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3727 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3728
3729 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003730 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003731 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003732 // Get mock reason string since we throw an IAE with empty string input.
3733 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3734 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003735
3736 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003737 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003738 MANAGED_PROFILE_USER_ID);
3739 }
3740
3741 public void testWipeDataManagedProfileDisallowed() throws Exception {
3742 final int MANAGED_PROFILE_USER_ID = 15;
3743 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3744 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3745
3746 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003747 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003748 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3749
Pavel Grafov75c0a892017-05-18 17:28:27 +01003750 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003751 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3752 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3753 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003754 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3755 thenReturn("Just a test string.");
3756
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003757 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003758 // The PO is not allowed to remove the profile if the user restriction was set on the
3759 // profile by the system
3760 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3761 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003762 }
3763
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003764 public void testWipeDataDeviceOwner() throws Exception {
3765 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003766 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003767 UserManager.DISALLOW_FACTORY_RESET,
3768 UserHandle.SYSTEM))
3769 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003770 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3771 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003772
3773 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003774 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003775 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3776 /*wipeEuicc=*/ eq(false));
3777 }
3778
3779 public void testWipeEuiccDataEnabled() throws Exception {
3780 setDeviceOwner();
3781 when(getServices().userManager.getUserRestrictionSource(
3782 UserManager.DISALLOW_FACTORY_RESET,
3783 UserHandle.SYSTEM))
3784 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003785 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3786 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003787
3788 dpm.wipeData(WIPE_EUICC);
3789 verify(getServices().recoverySystem).rebootWipeUserData(
3790 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3791 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003792 }
3793
3794 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3795 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003796 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003797 UserManager.DISALLOW_FACTORY_RESET,
3798 UserHandle.SYSTEM))
3799 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003800 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3801 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003802 // The DO is not allowed to wipe the device if the user restriction was set
3803 // by the system
3804 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3805 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003806 }
3807
3808 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3809 final int MANAGED_PROFILE_USER_ID = 15;
3810 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3811 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3812
3813 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003814 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003815 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3816
Pavel Grafov75c0a892017-05-18 17:28:27 +01003817 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003818 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3819 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3820 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3821
3822 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3823 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3824
3825 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3826 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3827 // Failed password attempts on the parent user are taken into account, as there isn't a
3828 // separate work challenge.
3829 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3830 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3831 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3832
3833 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3834 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003835 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003836 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003837 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003838 }
3839
3840 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3841 throws Exception {
3842 final int MANAGED_PROFILE_USER_ID = 15;
3843 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3844 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3845
3846 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003847 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003848 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3849
Pavel Grafov75c0a892017-05-18 17:28:27 +01003850 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003851 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3852 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3853 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3854
3855 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3856 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3857
3858 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3859 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3860 // Failed password attempts on the parent user are taken into account, as there isn't a
3861 // separate work challenge.
3862 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3863 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3864 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3865
3866 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3867 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003868 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003869 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003870 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003871 }
3872
3873 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3874 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003875 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003876 UserManager.DISALLOW_FACTORY_RESET,
3877 UserHandle.SYSTEM))
3878 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3879
3880 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3881
3882 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3883 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3884 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3885 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3886 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3887
3888 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3889 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003890 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003891 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3892 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003893 }
3894
3895 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3896 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003897 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003898 UserManager.DISALLOW_FACTORY_RESET,
3899 UserHandle.SYSTEM))
3900 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3901
3902 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3903
3904 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3905 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3906 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3907 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3908 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3909
3910 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003911 verifyZeroInteractions(getServices().recoverySystem);
3912 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003913 .removeUserEvenWhenDisallowed(anyInt());
3914 }
3915
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003916 public void testGetPermissionGrantState() throws Exception {
3917 final String permission = "some.permission";
3918 final String app1 = "com.example.app1";
3919 final String app2 = "com.example.app2";
3920
Pavel Grafov75c0a892017-05-18 17:28:27 +01003921 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003922 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003923 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003924 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003925 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003926 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3927 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003928 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003929 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003930 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003931 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003932 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003933 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3934
3935 // System can retrieve permission grant state.
3936 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003937 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003938 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3939 dpm.getPermissionGrantState(null, app1, permission));
3940 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3941 dpm.getPermissionGrantState(null, app2, permission));
3942
3943 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003944 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3945 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003946 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3947 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003948
3949 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003950 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3951 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003952 setAsProfileOwner(admin1);
3953 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3954 dpm.getPermissionGrantState(admin1, app1, permission));
3955 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3956 dpm.getPermissionGrantState(admin1, app2, permission));
3957 }
3958
Rubin Xuaab7a412016-12-30 21:13:29 +00003959 public void testResetPasswordWithToken() throws Exception {
3960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3961 setupDeviceOwner();
3962 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003963 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3964 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
3965
Rubin Xuaab7a412016-12-30 21:13:29 +00003966 // test adding a token
3967 final byte[] token = new byte[32];
3968 final long handle = 123456;
3969 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01003970 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003971 .thenReturn(handle);
3972 assertTrue(dpm.setResetPasswordToken(admin1, token));
3973
3974 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01003975 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003976 .thenReturn(true);
3977 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3978
3979 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003980 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01003981 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
3982 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00003983 eq(UserHandle.USER_SYSTEM)))
3984 .thenReturn(true);
3985 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3986
3987 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01003988 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00003989 .thenReturn(true);
3990 assertTrue(dpm.clearResetPasswordToken(admin1));
3991 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003992
Alexandru-Andrei Rotaru7f31bb02017-09-07 16:29:48 +01003993 public void testSetPasswordBlacklistCannotBeCalledByNonAdmin() throws Exception {
3994 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3995 () -> dpm.setPasswordBlacklist(admin1, null, null));
3996 verifyZeroInteractions(getServices().passwordBlacklist);
3997 }
3998
3999 public void testClearingPasswordBlacklistDoesNotCreateNewBlacklist() throws Exception {
4000 setupProfileOwner();
4001 dpm.setPasswordBlacklist(admin1, null, null);
4002 verifyZeroInteractions(getServices().passwordBlacklist);
4003 }
4004
4005 public void testSetPasswordBlacklistCreatesNewBlacklist() throws Exception {
4006 final String name = "myblacklist";
4007 final List<String> explicit = Arrays.asList("password", "letmein");
4008 setupProfileOwner();
4009 dpm.setPasswordBlacklist(admin1, name, explicit);
4010 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, explicit);
4011 }
4012
4013 public void testSetPasswordBlacklistOnlyConvertsExplicitToLowerCase() throws Exception {
4014 final List<String> mixedCase = Arrays.asList("password", "LETMEIN", "FooTBAll");
4015 final List<String> lowerCase = Arrays.asList("password", "letmein", "football");
4016 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4017 setupDeviceOwner();
4018 final String name = "Name of the Blacklist";
4019 dpm.setPasswordBlacklist(admin1, name, mixedCase);
4020 verify(getServices().passwordBlacklist).savePasswordBlacklist(name, lowerCase);
4021 }
4022
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004023 public void testIsActivePasswordSufficient() throws Exception {
4024 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4025 mContext.packageName = admin1.getPackageName();
4026 setupDeviceOwner();
4027
4028 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4029 dpm.setPasswordMinimumLength(admin1, 8);
4030 dpm.setPasswordMinimumLetters(admin1, 6);
4031 dpm.setPasswordMinimumLowerCase(admin1, 3);
4032 dpm.setPasswordMinimumUpperCase(admin1, 1);
4033 dpm.setPasswordMinimumNonLetter(admin1, 1);
4034 dpm.setPasswordMinimumNumeric(admin1, 1);
4035 dpm.setPasswordMinimumSymbols(admin1, 0);
4036
Rubin Xucc391c22018-01-02 20:37:35 +00004037 reset(mContext.spiedContext);
4038
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004039 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4040 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4041 8, 2,
4042 6, 1,
4043 0, 1);
4044
4045 setActivePasswordState(passwordMetricsNoSymbols);
4046 assertTrue(dpm.isActivePasswordSufficient());
4047
4048 initializeDpms();
4049 reset(mContext.spiedContext);
4050 assertTrue(dpm.isActivePasswordSufficient());
4051
4052 // This call simulates the user entering the password for the first time after a reboot.
4053 // This causes password metrics to be reloaded into memory. Until this happens,
4054 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4055 // even if the DPC changes password requirements so that the password no longer meets the
4056 // requirements. This is a known limitation of the current implementation of
4057 // isActivePasswordSufficient() - see b/34218769.
4058 setActivePasswordState(passwordMetricsNoSymbols);
4059 assertTrue(dpm.isActivePasswordSufficient());
4060
4061 dpm.setPasswordMinimumSymbols(admin1, 1);
4062 // This assertion would fail if we had not called setActivePasswordState() again after
4063 // initializeDpms() - see previous comment.
4064 assertFalse(dpm.isActivePasswordSufficient());
4065
4066 initializeDpms();
4067 reset(mContext.spiedContext);
4068 assertFalse(dpm.isActivePasswordSufficient());
4069
4070 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4071 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4072 7, 2,
4073 5, 1,
4074 1, 2);
4075
4076 setActivePasswordState(passwordMetricsWithSymbols);
4077 assertTrue(dpm.isActivePasswordSufficient());
4078 }
4079
Pavel Grafov75c0a892017-05-18 17:28:27 +01004080 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4081 throws Exception {
4082 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004083 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004084
Pavel Grafov75c0a892017-05-18 17:28:27 +01004085 dpm.setActivePasswordState(passwordMetrics, userHandle);
4086 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004087
Rubin Xucc391c22018-01-02 20:37:35 +00004088 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4089 // reportPasswordChanged()
4090 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
4091 MockUtils.checkIntentAction(
4092 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4093 MockUtils.checkUserHandle(userHandle));
4094
Pavel Grafov75c0a892017-05-18 17:28:27 +01004095 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4096 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004097 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004098
4099 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4100 MockUtils.checkIntent(intent),
4101 MockUtils.checkUserHandle(userHandle));
4102
4103 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4104 // let it finish with system uid, otherwise it will throw and crash.
4105 flushTasks();
4106
4107 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004108 }
4109
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004110 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4111 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4112 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4113 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4114 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4115 DpmMockContext.SYSTEM_UID);
4116 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4117 DpmMockContext.SYSTEM_UID);
4118
4119 // Set up a device owner.
4120 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004121 setupDeviceOwner();
4122
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004123 // First and second user set IMEs manually.
4124 mContext.binder.callingUid = firstUserSystemUid;
4125 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4126 mContext.binder.callingUid = secondUserSystemUid;
4127 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004128
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004129 // Device owner changes IME for first user.
4130 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004131 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004132 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004133 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004135 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004136 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004137 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4138 mContext.binder.callingUid = firstUserSystemUid;
4139 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4140 mContext.binder.callingUid = secondUserSystemUid;
4141 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004142
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004143 // Second user changes IME manually.
4144 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4145 mContext.binder.callingUid = firstUserSystemUid;
4146 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4147 mContext.binder.callingUid = secondUserSystemUid;
4148 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004149
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004150 // First user changes IME manually.
4151 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4152 mContext.binder.callingUid = firstUserSystemUid;
4153 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4154 mContext.binder.callingUid = secondUserSystemUid;
4155 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004156
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004157 // Device owner changes IME for first user again.
4158 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004159 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004160 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004161 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004163 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004164 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4165 mContext.binder.callingUid = firstUserSystemUid;
4166 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4167 mContext.binder.callingUid = secondUserSystemUid;
4168 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004169
4170 // Restarting the DPMS should not lose information.
4171 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004172 mContext.binder.callingUid = firstUserSystemUid;
4173 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4174 mContext.binder.callingUid = secondUserSystemUid;
4175 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004176
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004177 // Device owner can find out whether it set the current IME itself.
4178 mContext.binder.callingUid = deviceOwnerUid;
4179 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004180
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004181 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004182 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004183 mContext.binder.callingUid = firstUserSystemUid;
4184 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4185 mContext.binder.callingUid = secondUserSystemUid;
4186 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004187 }
4188
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004189 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4190 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4191 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4192 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4193 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4194 DpmMockContext.SYSTEM_UID);
4195 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4196 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004197
4198 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004199 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004200 setupProfileOwner();
4201
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004202 // First and second user set IMEs manually.
4203 mContext.binder.callingUid = firstUserSystemUid;
4204 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4205 mContext.binder.callingUid = secondUserSystemUid;
4206 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004207
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004208 // Profile owner changes IME for second user.
4209 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004210 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004211 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004212 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004213 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004214 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004215 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004216 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4217 mContext.binder.callingUid = firstUserSystemUid;
4218 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4219 mContext.binder.callingUid = secondUserSystemUid;
4220 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004221
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004222 // First user changes IME manually.
4223 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4224 mContext.binder.callingUid = firstUserSystemUid;
4225 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4226 mContext.binder.callingUid = secondUserSystemUid;
4227 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004228
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004229 // Second user changes IME manually.
4230 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4231 mContext.binder.callingUid = firstUserSystemUid;
4232 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4233 mContext.binder.callingUid = secondUserSystemUid;
4234 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004235
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004236 // Profile owner changes IME for second user again.
4237 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004238 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004239 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004240 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004241 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004242 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004243 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4244 mContext.binder.callingUid = firstUserSystemUid;
4245 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4246 mContext.binder.callingUid = secondUserSystemUid;
4247 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004248
4249 // Restarting the DPMS should not lose information.
4250 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004251 mContext.binder.callingUid = firstUserSystemUid;
4252 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4253 mContext.binder.callingUid = secondUserSystemUid;
4254 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004255
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004256 // Profile owner can find out whether it set the current IME itself.
4257 mContext.binder.callingUid = profileOwnerUid;
4258 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004259
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004260 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004261 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004262 mContext.binder.callingUid = firstUserSystemUid;
4263 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4264 mContext.binder.callingUid = secondUserSystemUid;
4265 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004266 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004267
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004268 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4269 throws Exception {
4270 // Set up a device owner.
4271 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4272 setupDeviceOwner();
4273 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4274 }
4275
4276 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4277 throws Exception {
4278 // Set up a profile owner.
4279 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4280 setupProfileOwner();
4281 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4282 }
4283
4284 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4285 int adminUid) throws Exception {
4286 mContext.binder.callingUid = adminUid;
4287 final int userId = UserHandle.getUserId(adminUid);
4288
4289 final String packageName = "some.package";
4290 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4291 admin1, Collections.singletonList(packageName)));
4292 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4293
4294 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4295 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4296
4297 // Attempt to set to empty list (which means no listener is whitelisted)
4298 mContext.binder.callingUid = adminUid;
4299 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004300 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004301 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4302
4303 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4304 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4305 }
4306
4307 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4308 // Set up a managed profile
4309 final int MANAGED_PROFILE_USER_ID = 15;
4310 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4311 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4312 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4313
4314 final String permittedListener = "some.package";
4315 setupPackageInPackageManager(
4316 permittedListener,
4317 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4318 /*appId=*/ 12345, /*flags=*/ 0);
4319
4320 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4321 admin1, Collections.singletonList(permittedListener)));
4322
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004323 // isNotificationListenerServicePermitted should throw if not called from System.
4324 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4325 () -> dpms.isNotificationListenerServicePermitted(
4326 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004327
4328 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4329 assertTrue(dpms.isNotificationListenerServicePermitted(
4330 permittedListener, MANAGED_PROFILE_USER_ID));
4331 }
4332
4333 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4334 throws Exception {
4335 // Set up a managed profile
4336 final int MANAGED_PROFILE_USER_ID = 15;
4337 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4338 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4339 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4340
4341 final String permittedListener = "permitted.package";
4342 int appId = 12345;
4343 setupPackageInPackageManager(
4344 permittedListener,
4345 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4346 appId, /*flags=*/ 0);
4347
4348 final String notPermittedListener = "not.permitted.package";
4349 setupPackageInPackageManager(
4350 notPermittedListener,
4351 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4352 ++appId, /*flags=*/ 0);
4353
4354 final String systemListener = "system.package";
4355 setupPackageInPackageManager(
4356 systemListener,
4357 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4358 ++appId, ApplicationInfo.FLAG_SYSTEM);
4359
4360 // By default all packages are allowed
4361 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4362
4363 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4364 assertTrue(dpms.isNotificationListenerServicePermitted(
4365 permittedListener, MANAGED_PROFILE_USER_ID));
4366 assertTrue(dpms.isNotificationListenerServicePermitted(
4367 notPermittedListener, MANAGED_PROFILE_USER_ID));
4368 assertTrue(dpms.isNotificationListenerServicePermitted(
4369 systemListener, MANAGED_PROFILE_USER_ID));
4370
4371 // Setting only one package in the whitelist
4372 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4373 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4374 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004375 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004376 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4377 assertEquals(1, permittedListeners.size());
4378 assertEquals(permittedListener, permittedListeners.get(0));
4379
4380 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4381 assertTrue(dpms.isNotificationListenerServicePermitted(
4382 permittedListener, MANAGED_PROFILE_USER_ID));
4383 assertFalse(dpms.isNotificationListenerServicePermitted(
4384 notPermittedListener, MANAGED_PROFILE_USER_ID));
4385 // System packages are always allowed (even if not in the whitelist)
4386 assertTrue(dpms.isNotificationListenerServicePermitted(
4387 systemListener, MANAGED_PROFILE_USER_ID));
4388
4389 // Setting an empty whitelist - only system listeners allowed
4390 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4391 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004392 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004393 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4394
4395 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4396 assertFalse(dpms.isNotificationListenerServicePermitted(
4397 permittedListener, MANAGED_PROFILE_USER_ID));
4398 assertFalse(dpms.isNotificationListenerServicePermitted(
4399 notPermittedListener, MANAGED_PROFILE_USER_ID));
4400 // System packages are always allowed (even if not in the whitelist)
4401 assertTrue(dpms.isNotificationListenerServicePermitted(
4402 systemListener, MANAGED_PROFILE_USER_ID));
4403
4404 // Setting a null whitelist - all listeners allowed
4405 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4406 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4407 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4408
4409 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4410 assertTrue(dpms.isNotificationListenerServicePermitted(
4411 permittedListener, MANAGED_PROFILE_USER_ID));
4412 assertTrue(dpms.isNotificationListenerServicePermitted(
4413 notPermittedListener, MANAGED_PROFILE_USER_ID));
4414 assertTrue(dpms.isNotificationListenerServicePermitted(
4415 systemListener, MANAGED_PROFILE_USER_ID));
4416 }
4417
4418 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4419 throws Exception {
4420 // Set up a managed profile
4421 final int MANAGED_PROFILE_USER_ID = 15;
4422 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4423 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4424 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4425
4426 final String nonSystemPackage = "non.system.package";
4427 int appId = 12345;
4428 setupPackageInPackageManager(
4429 nonSystemPackage,
4430 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4431 appId, /*flags=*/ 0);
4432
4433 final String systemListener = "system.package";
4434 setupPackageInPackageManager(
4435 systemListener,
4436 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4437 ++appId, ApplicationInfo.FLAG_SYSTEM);
4438
4439 // By default all packages are allowed (for all profiles)
4440 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4441
4442 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4443 assertTrue(dpms.isNotificationListenerServicePermitted(
4444 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4445 assertTrue(dpms.isNotificationListenerServicePermitted(
4446 systemListener, MANAGED_PROFILE_USER_ID));
4447 assertTrue(dpms.isNotificationListenerServicePermitted(
4448 nonSystemPackage, UserHandle.USER_SYSTEM));
4449 assertTrue(dpms.isNotificationListenerServicePermitted(
4450 systemListener, UserHandle.USER_SYSTEM));
4451
4452 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4453 // all allowed in primary profile
4454 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4455 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004456 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004457 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4458
4459 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4460 assertFalse(dpms.isNotificationListenerServicePermitted(
4461 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4462 assertTrue(dpms.isNotificationListenerServicePermitted(
4463 systemListener, MANAGED_PROFILE_USER_ID));
4464 assertTrue(dpms.isNotificationListenerServicePermitted(
4465 nonSystemPackage, UserHandle.USER_SYSTEM));
4466 assertTrue(dpms.isNotificationListenerServicePermitted(
4467 systemListener, UserHandle.USER_SYSTEM));
4468 }
4469
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004470 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004471 mServiceContext.packageName = mRealTestContext.getPackageName();
4472 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4473 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004474 setDeviceOwner();
4475
Pavel Grafov75c0a892017-05-18 17:28:27 +01004476 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004477 }
4478
4479 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004480 mServiceContext.packageName = mRealTestContext.getPackageName();
4481 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4482 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004483 setAsProfileOwner(admin1);
4484
Pavel Grafov75c0a892017-05-18 17:28:27 +01004485 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4486 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004487 }
4488
4489 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004490 mServiceContext.packageName = mRealTestContext.getPackageName();
4491 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4492 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004493 setAsProfileOwner(admin1);
4494
Pavel Grafov75c0a892017-05-18 17:28:27 +01004495 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4496 caller.packageName = "com.example.delegate";
4497 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4498 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004499
Pavel Grafov75c0a892017-05-18 17:28:27 +01004500 // Make caller a delegated cert installer.
4501 runAsCaller(mAdmin1Context, dpms,
4502 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004503
4504 verifyCanGetOwnerInstalledCaCerts(null, caller);
4505 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004506 }
4507
Rubin Xucc391c22018-01-02 20:37:35 +00004508 public void testDisallowSharingIntoProfileSetRestriction() {
4509 Bundle restriction = new Bundle();
4510 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4511
4512 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4513 RestrictionsListener listener = new RestrictionsListener(mContext);
4514 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4515 new Bundle());
4516 verifyDataSharingChangedBroadcast();
4517 }
4518
4519 public void testDisallowSharingIntoProfileClearRestriction() {
4520 Bundle restriction = new Bundle();
4521 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4522
4523 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4524 RestrictionsListener listener = new RestrictionsListener(mContext);
4525 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4526 restriction);
4527 verifyDataSharingChangedBroadcast();
4528 }
4529
4530 public void testDisallowSharingIntoProfileUnchanged() {
4531 RestrictionsListener listener = new RestrictionsListener(mContext);
4532 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4533 new Bundle());
4534 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4535 }
4536
4537 private void verifyDataSharingChangedBroadcast() {
4538 Intent expectedIntent = new Intent(
4539 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4540 expectedIntent.setPackage("com.android.managedprovisioning");
4541 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4542 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4543 MockUtils.checkIntent(expectedIntent),
4544 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4545 }
4546
Robin Lee2c68dad2017-03-17 12:50:24 +00004547 private void verifyCanGetOwnerInstalledCaCerts(
4548 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004549 final String alias = "cert";
4550 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004551
4552 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004553 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004554 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4555 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004556 }
4557 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4558
4559 // caller: device admin or delegated certificate installer
4560 callerContext.applicationInfo = new ApplicationInfo();
4561 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4562
4563 // system_server
4564 final DpmMockContext serviceContext = mContext;
4565 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004566 getServices().addPackageContext(callerUser, admin1Context);
4567 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004568
4569 // Install a CA cert.
4570 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004571 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004572 .thenReturn(alias);
4573 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004574 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004575 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004576 });
4577
Pavel Grafov75c0a892017-05-18 17:28:27 +01004578 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4579 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4580 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004581 flushTasks();
4582
Robin Lee2c68dad2017-03-17 12:50:24 +00004583 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4584
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004585 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004586 runAsCaller(admin1Context, dpms, (dpm) -> {
4587 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004588 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004589 ownerInstalledCaCerts.addAll(installedCaCerts);
4590 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004591
4592 // Restarting the DPMS should not lose information.
4593 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004594 runAsCaller(admin1Context, dpms, (dpm) ->
4595 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004596
4597 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004598 runAsCaller(serviceContext, dpms, (dpm) -> {
4599 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004600
Robin Lee2c68dad2017-03-17 12:50:24 +00004601 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004602 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004603 });
4604
Pavel Grafov75c0a892017-05-18 17:28:27 +01004605 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4606 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4607 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004608 flushTasks();
4609
4610 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4611 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004612 runAsCaller(admin1Context, dpms, (dpm) -> {
4613 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4614 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004615 }
4616
Robin Lee2c68dad2017-03-17 12:50:24 +00004617 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4618 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004619 final String alias = "cert";
4620 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004621
4622 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004623 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004624 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4625 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004626 }
4627 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4628
4629 // caller: device admin or delegated certificate installer
4630 callerContext.applicationInfo = new ApplicationInfo();
4631 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4632
4633 // system_server
4634 final DpmMockContext serviceContext = mContext;
4635 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004636 getServices().addPackageContext(callerUser, admin1Context);
4637 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004638
4639 // Install a CA cert as caller
4640 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004641 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004642 .thenReturn(alias);
4643 assertTrue(dpm.installCaCert(callerName, caCert));
4644 });
4645
4646 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004647 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004648 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004649 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4650 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4651 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004652 flushTasks();
4653
Robin Lee2c68dad2017-03-17 12:50:24 +00004654 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004655 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004656
4657 runAsCaller(serviceContext, dpms, (dpm) -> {
4658 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4659 assertNotNull(ownerInstalledCaCerts);
4660 assertTrue(ownerInstalledCaCerts.isEmpty());
4661 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004662 }
4663
Eran Messeri94d56762017-12-21 20:50:54 +00004664 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4665 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4666 Arrays.sort(gotFlags);
4667 Arrays.sort(expectedFlags);
4668 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4669 }
4670
4671 public void testTranslationOfIdAttestationFlag() {
4672 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4673 int[] correspondingAttUtilsTypes = new int[]{
4674 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4675 AttestationUtils.ID_TYPE_MEID};
4676
4677 // Test translation of zero flags
4678 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4679
4680 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4681 // non-null array
4682 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4683
4684 // Test translation of a single flag
4685 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4686 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4687 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4688
4689 // Test translation of two flags
4690 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4691 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4692 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4693 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4694
4695 // Test translation of all three flags
4696 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4697 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4698 AttestationUtils.ID_TYPE_MEID});
4699 // Test translation of all three flags
4700 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4701 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4702 AttestationUtils.ID_TYPE_MEID});
4703 }
4704
Victor Chang3e794af2016-03-04 13:48:17 +00004705 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004706 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00004707 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4708 dpms.notifyChangeToContentObserver(
4709 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4710 }
4711
4712 private void assertProvisioningAllowed(String action, boolean expected) {
4713 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4714 dpm.isProvisioningAllowed(action));
4715 }
Tony Mak2f26b792016-11-28 17:54:51 +00004716
Nicolas Prevot45d29072017-01-18 16:11:19 +00004717 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4718 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004719 final String previousPackageName = mContext.packageName;
4720 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00004721
4722 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4723 mContext.packageName = packageName;
4724 mMockContext.binder.callingUid = uid;
4725 assertProvisioningAllowed(action, expected);
4726
4727 // Set the previous package name / calling uid to go back to the initial state.
4728 mContext.packageName = previousPackageName;
4729 mMockContext.binder.callingUid = previousUid;
4730 }
4731
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004732 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004733 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4734 }
4735
4736 private void assertCheckProvisioningPreCondition(
4737 String action, String packageName, int provisioningCondition) {
4738 assertEquals("checkProvisioningPreCondition("
4739 + action + ", " + packageName + ") returning unexpected result",
4740 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004741 }
4742
Tony Mak2f26b792016-11-28 17:54:51 +00004743 /**
4744 * Setup a managed profile with the specified admin and its uid.
4745 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4746 * @param adminUid uid of the admin package.
4747 * @param copyFromAdmin package information for {@code admin} will be built based on this
4748 * component's information.
4749 */
4750 private void addManagedProfile(
4751 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4752 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004753 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00004754 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4755 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4756 dpm.setActiveAdmin(admin, false, userId);
4757 assertTrue(dpm.setProfileOwner(admin, null, userId));
4758 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4759 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004760
4761 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004762 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004763 */
Robin Leeabaa0692017-02-20 20:54:22 +00004764 private static StringParceledListSlice asSlice(String[] s) {
4765 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004766 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004767
4768 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004769 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4770 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004771
Robin Lee2c68dad2017-03-17 12:50:24 +00004772 // We can't let exceptions happen on the background thread. Throw them here if they happen
4773 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004774 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004775 }
Victor Chang3e794af2016-03-04 13:48:17 +00004776}