blob: 2a1c3db5f68288d0d92f5295e6f151d03c97e2cf [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;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010028import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
29import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
30import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
31
Eugene Susla4f8680b2017-08-07 17:25:30 -070032import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010033
Pavel Grafov75c0a892017-05-18 17:28:27 +010034import static org.mockito.Matchers.any;
35import static org.mockito.Matchers.anyInt;
36import static org.mockito.Matchers.anyLong;
37import static org.mockito.Matchers.anyObject;
38import static org.mockito.Matchers.anyString;
39import static org.mockito.Matchers.eq;
40import static org.mockito.Matchers.isNull;
41import static org.mockito.Mockito.atLeast;
42import static org.mockito.Mockito.doAnswer;
43import static org.mockito.Mockito.doReturn;
44import static org.mockito.Mockito.never;
45import static org.mockito.Mockito.nullable;
46import static org.mockito.Mockito.reset;
47import static org.mockito.Mockito.timeout;
48import static org.mockito.Mockito.times;
49import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080050import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010051import static org.mockito.Mockito.verifyZeroInteractions;
52import static org.mockito.Mockito.when;
53import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000054import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010055
Makoto Onukif76b06a2015-09-22 15:03:44 -070056import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000057import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000059import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060import android.app.admin.DeviceAdminReceiver;
61import android.app.admin.DevicePolicyManager;
62import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010063import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070064import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000066import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000067import android.content.pm.ApplicationInfo;
68import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070069import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010070import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000071import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000072import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010073import android.graphics.Color;
74import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080075import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080076import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070077import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080078import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070079import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070080import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010081import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080082import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010083import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000084import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000085import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000086import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080087import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000088import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010089import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070090import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010092import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000093import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000094import com.android.server.LocalServices;
95import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000096import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000097import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000098
Robin Lee7f5c91c2017-02-08 21:27:02 +000099import org.hamcrest.BaseMatcher;
100import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800101import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700102import org.mockito.invocation.InvocationOnMock;
103import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104
arangelov08d534b2018-01-22 15:20:53 +0000105import java.io.File;
106import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800107import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000108import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000109import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700110import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700112import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100113import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000114import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700117 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000118 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119 m FrameworksServicesTests &&
120 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000121 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700123 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124
125 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000126 *
127 * , or:
128 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000130@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100131@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700132public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000133 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
134 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
135 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100136 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800137 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100138 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000139
Pavel Grafov75c0a892017-05-18 17:28:27 +0100140 // TODO replace all instances of this with explicit {@link #mServiceContext}.
141 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700142 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100143
144 private DpmMockContext mServiceContext;
145 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700146 public DevicePolicyManager dpm;
147 public DevicePolicyManagerServiceTestable dpms;
148
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100149 /*
150 * The CA cert below is the content of cacert.pem as generated by:
151 *
152 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
153 */
154 private static final String TEST_CA =
155 "-----BEGIN CERTIFICATE-----\n" +
156 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
157 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
158 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
159 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
160 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
161 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
162 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
163 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
164 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
165 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
166 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
167 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
168 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
169 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
170 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
171 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
172 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
173 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
174 "wQ==\n" +
175 "-----END CERTIFICATE-----\n";
176
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700177 @Override
178 protected void setUp() throws Exception {
179 super.setUp();
180
181 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100182 mServiceContext = mContext;
183 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
184 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700185 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100186 doReturn(Collections.singletonList(new ResolveInfo()))
187 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
188 any(Intent.class),
189 anyInt(),
190 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700191
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800192 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100193 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800194
Makoto Onukia52562c2015-10-01 16:12:31 -0700195 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700196
Sudheer Shanka101c3532018-01-08 16:28:42 -0800197 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800198 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700199 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
200 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
201 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800202 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700203
Pavel Grafov75c0a892017-05-18 17:28:27 +0100204 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
205 mAdmin1Context.packageName = admin1.getPackageName();
206 mAdmin1Context.applicationInfo = new ApplicationInfo();
207 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
208
Makoto Onukib643fb02015-09-22 15:03:44 -0700209 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700210 }
211
arangelov08d534b2018-01-22 15:20:53 +0000212 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
213 return dpms.mTransferOwnershipMetadataManager;
214 }
215
Robin Lee2c68dad2017-03-17 12:50:24 +0000216 @Override
217 protected void tearDown() throws Exception {
218 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000219 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000220 super.tearDown();
221 }
222
Makoto Onukia52562c2015-10-01 16:12:31 -0700223 private void initializeDpms() {
224 // Need clearCallingIdentity() to pass permission checks.
225 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100226 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700227
Pavel Grafov75c0a892017-05-18 17:28:27 +0100228 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
229 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
230 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700231
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700233
Pavel Grafov75c0a892017-05-18 17:28:27 +0100234 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235 }
236
Makoto Onukib643fb02015-09-22 15:03:44 -0700237 private void setUpUserManager() {
238 // Emulate UserManager.set/getApplicationRestriction().
239 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
240
241 // UM.setApplicationRestrictions() will save to appRestrictions.
242 doAnswer(new Answer<Void>() {
243 @Override
244 public Void answer(InvocationOnMock invocation) throws Throwable {
245 String pkg = (String) invocation.getArguments()[0];
246 Bundle bundle = (Bundle) invocation.getArguments()[1];
247 UserHandle user = (UserHandle) invocation.getArguments()[2];
248
249 appRestrictions.put(Pair.create(pkg, user), bundle);
250
251 return null;
252 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100253 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100254 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
256 // UM.getApplicationRestrictions() will read from appRestrictions.
257 doAnswer(new Answer<Bundle>() {
258 @Override
259 public Bundle answer(InvocationOnMock invocation) throws Throwable {
260 String pkg = (String) invocation.getArguments()[0];
261 UserHandle user = (UserHandle) invocation.getArguments()[1];
262
263 return appRestrictions.get(Pair.create(pkg, user));
264 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700266 anyString(), any(UserHandle.class));
267
Makoto Onukid932f762015-09-29 16:53:38 -0700268 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100269 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700270 }
271
272 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700274
Pavel Grafov75c0a892017-05-18 17:28:27 +0100275 mServiceContext.binder.callingUid =
276 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
277 runAsCaller(mServiceContext, dpms, dpm -> {
278 // PO needs to be a DA.
279 dpm.setActiveAdmin(admin, /*replace=*/ false);
280 // Fire!
281 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
282 // Check
283 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
284 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700285
Pavel Grafov75c0a892017-05-18 17:28:27 +0100286 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700287 }
288
289 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100290 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291 .thenReturn(false);
292
293 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100294 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700295
296 // If the device has no DPMS feature, it shouldn't register the local service.
297 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
298 }
299
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800300 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800301 // Device owner in SYSTEM_USER
302 setDeviceOwner();
303 // Profile owner in CALLER_USER_HANDLE
304 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
305 setAsProfileOwner(admin2);
306 // Active admin in CALLER_USER_HANDLE
307 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
308 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
309 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
310 DpmMockContext.CALLER_USER_HANDLE);
311 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
312 DpmMockContext.CALLER_USER_HANDLE));
313
314 initializeDpms();
315
316 // Verify
317 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800318 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800319 eq(UserHandle.USER_SYSTEM));
320 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800321 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800322 adminAnotherPackage.getPackageName()),
323 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800324 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
325 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
326 }
327
328 public void testLoadAdminData_noAdmins() throws Exception {
329 final int ANOTHER_USER_ID = 15;
330 getServices().addUser(ANOTHER_USER_ID, 0);
331
332 initializeDpms();
333
334 // Verify
335 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
336 null, DpmMockContext.CALLER_USER_HANDLE);
337 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
338 null, ANOTHER_USER_ID);
339 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
340 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800341 }
342
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700343 /**
344 * Caller doesn't have proper permissions.
345 */
346 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700347 // 1. Failure cases.
348
349 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100350 assertExpectException(SecurityException.class, /* messageRegex= */ null,
351 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700352
353 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
354 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100355
356 assertExpectException(SecurityException.class, /* messageRegex= */ null,
357 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700358 }
359
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 /**
361 * Test for:
362 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800363 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700364 * {@link DevicePolicyManager#isAdminActive}
365 * {@link DevicePolicyManager#isAdminActiveAsUser}
366 * {@link DevicePolicyManager#getActiveAdmins}
367 * {@link DevicePolicyManager#getActiveAdminsAsUser}
368 */
369 public void testSetActiveAdmin() throws Exception {
370 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700371 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
372
Makoto Onukif76b06a2015-09-22 15:03:44 -0700373 // 2. Call the API.
374 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700375
376 // 3. Verify internal calls.
377
378 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700379 verify(mContext.spiedContext).sendBroadcastAsUser(
380 MockUtils.checkIntentAction(
381 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
382 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
383 verify(mContext.spiedContext).sendBroadcastAsUser(
384 MockUtils.checkIntentAction(
385 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700386 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
387
Pavel Grafov75c0a892017-05-18 17:28:27 +0100388 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389 eq(admin1.getPackageName()),
390 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
391 eq(PackageManager.DONT_KILL_APP),
392 eq(DpmMockContext.CALLER_USER_HANDLE),
393 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394
Sudheer Shanka101c3532018-01-08 16:28:42 -0800395 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
396 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
397
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700398 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700399
400 // Make sure it's active admin1.
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403 assertFalse(dpm.isAdminActive(admin3));
404
405 // But not admin1 for a different user.
406
407 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
408 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
409 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
412 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
413
414 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
415
416 // Next, add one more admin.
417 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700418 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700419 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700420
421 dpm.setActiveAdmin(admin2, /* replace =*/ false);
422
423 // Now we have two admins.
424 assertTrue(dpm.isAdminActive(admin1));
425 assertTrue(dpm.isAdminActive(admin2));
426 assertFalse(dpm.isAdminActive(admin3));
427
428 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
429 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100430 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431 eq(admin1.getPackageName()),
432 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
433 eq(PackageManager.DONT_KILL_APP),
434 eq(DpmMockContext.CALLER_USER_HANDLE),
435 anyString());
436
Sudheer Shanka101c3532018-01-08 16:28:42 -0800437 // times(2) because it was previously called for admin1 which is in the same package
438 // as admin2.
439 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
440 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
441
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100443 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
444 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445
446 // 5. Add the same admin1 again with replace, which should succeed.
447 dpm.setActiveAdmin(admin1, /* replace =*/ true);
448
449 // TODO make sure it's replaced.
450
451 // 6. Test getActiveAdmins()
452 List<ComponentName> admins = dpm.getActiveAdmins();
453 assertEquals(2, admins.size());
454 assertEquals(admin1, admins.get(0));
455 assertEquals(admin2, admins.get(1));
456
Sudheer Shanka101c3532018-01-08 16:28:42 -0800457 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
458 // replaced
459 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
460
Makoto Onukif76b06a2015-09-22 15:03:44 -0700461 // Another user has no admins.
462 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
463
464 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
465 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
466
467 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
468 }
469
Makoto Onukid932f762015-09-29 16:53:38 -0700470 public void testSetActiveAdmin_multiUsers() throws Exception {
471
472 final int ANOTHER_USER_ID = 100;
473 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
474
Pavel Grafov75c0a892017-05-18 17:28:27 +0100475 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 // Set up pacakge manager for the other user.
478 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
481
482 dpm.setActiveAdmin(admin1, /* replace =*/ false);
483
484 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
485 dpm.setActiveAdmin(admin2, /* replace =*/ false);
486
487
488 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
489 assertTrue(dpm.isAdminActive(admin1));
490 assertFalse(dpm.isAdminActive(admin2));
491
492 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
493 assertFalse(dpm.isAdminActive(admin1));
494 assertTrue(dpm.isAdminActive(admin2));
495 }
496
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 /**
498 * Test for:
499 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800500 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700501 */
502 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
503 // 1. Make sure the caller has proper permissions.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506 dpm.setActiveAdmin(admin1, /* replace =*/ false);
507 assertTrue(dpm.isAdminActive(admin1));
508
509 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
511 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700512 }
513
514 /**
515 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800516 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
517 * BIND_DEVICE_ADMIN.
518 */
519 public void testSetActiveAdmin_permissionCheck() throws Exception {
520 // 1. Make sure the caller has proper permissions.
521 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
522
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(IllegalArgumentException.class,
524 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
525 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800526 assertFalse(dpm.isAdminActive(adminNoPerm));
527
528 // Change the target API level to MNC. Now it can be set as DA.
529 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
530 VERSION_CODES.M);
531 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
532 assertTrue(dpm.isAdminActive(adminNoPerm));
533
534 // TODO Test the "load from the file" case where DA will still be loaded even without
535 // BIND_DEVICE_ADMIN and target API is N.
536 }
537
538 /**
539 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700540 * {@link DevicePolicyManager#removeActiveAdmin}
541 */
542 public void testRemoveActiveAdmin_SecurityException() {
543 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
544
545 // Add admin.
546
547 dpm.setActiveAdmin(admin1, /* replace =*/ false);
548
549 assertTrue(dpm.isAdminActive(admin1));
550
551 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
552
553 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100554 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
555 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700556
557 // Try to remove active admin with a different caller userid should fail too, without
558 // having MANAGE_DEVICE_ADMINS.
559 mContext.callerPermissions.clear();
560
Makoto Onukid932f762015-09-29 16:53:38 -0700561 // Change the caller, and call into DPMS directly with a different user-id.
562
Makoto Onukif76b06a2015-09-22 15:03:44 -0700563 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100564 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
565 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 }
567
568 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800569 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
570 * (because we can't send the remove broadcast).
571 */
572 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
573 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
574
575 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
576
577 // Add admin.
578
579 dpm.setActiveAdmin(admin1, /* replace =*/ false);
580
581 assertTrue(dpm.isAdminActive(admin1));
582
583 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
584
585 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100586 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100588 assertExpectException(IllegalStateException.class,
589 /* messageRegex= */ "User must be running and unlocked",
590 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800593 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
594 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800595
596 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100597 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598 .thenReturn(true);
599
600 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700601 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800602 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
603 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800604 }
605
606 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 * Test for:
608 * {@link DevicePolicyManager#removeActiveAdmin}
609 */
Makoto Onukid932f762015-09-29 16:53:38 -0700610 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700611 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
612
613 // Add admin1.
614
615 dpm.setActiveAdmin(admin1, /* replace =*/ false);
616
617 assertTrue(dpm.isAdminActive(admin1));
618 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
619
620 // Different user, but should work, because caller has proper permissions.
621 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700622
623 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700624 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700627 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800628 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
629 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700630
631 // TODO DO Still can't be removed in this case.
632 }
633
634 /**
635 * Test for:
636 * {@link DevicePolicyManager#removeActiveAdmin}
637 */
638 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
639 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
640 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
641
642 // Add admin1.
643
644 dpm.setActiveAdmin(admin1, /* replace =*/ false);
645
646 assertTrue(dpm.isAdminActive(admin1));
647 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
648
649 // Broadcast from saveSettingsLocked().
650 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
651 MockUtils.checkIntentAction(
652 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
653 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
654
655 // Remove. No permissions, but same user, so it'll work.
656 mContext.callerPermissions.clear();
657 dpm.removeActiveAdmin(admin1);
658
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
660 MockUtils.checkIntentAction(
661 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
662 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
663 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700664 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700665 eq(dpms.mHandler),
666 eq(Activity.RESULT_OK),
667 isNull(String.class),
668 isNull(Bundle.class));
669
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700670 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800671 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
672 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700673
674 // Again broadcast from saveSettingsLocked().
675 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
676 MockUtils.checkIntentAction(
677 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
678 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
679
680 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700681 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700682
Sudheer Shanka101c3532018-01-08 16:28:42 -0800683 public void testRemoveActiveAdmin_multipleAdminsInUser() {
684 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
685 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
686
687 // Add admin1.
688 dpm.setActiveAdmin(admin1, /* replace =*/ false);
689
690 assertTrue(dpm.isAdminActive(admin1));
691 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
692
693 // Add admin2.
694 dpm.setActiveAdmin(admin2, /* replace =*/ false);
695
696 assertTrue(dpm.isAdminActive(admin2));
697 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
698
699 // Broadcast from saveSettingsLocked().
700 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
701 MockUtils.checkIntentAction(
702 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
703 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
704
705 // Remove. No permissions, but same user, so it'll work.
706 mContext.callerPermissions.clear();
707 dpm.removeActiveAdmin(admin1);
708
709 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
710 MockUtils.checkIntentAction(
711 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
712 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
713 isNull(String.class),
714 any(BroadcastReceiver.class),
715 eq(dpms.mHandler),
716 eq(Activity.RESULT_OK),
717 isNull(String.class),
718 isNull(Bundle.class));
719
720 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
721 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800722 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800723 eq(DpmMockContext.CALLER_USER_HANDLE));
724
725 // Again broadcast from saveSettingsLocked().
726 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
727 MockUtils.checkIntentAction(
728 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
729 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
730 }
731
732 /**
733 * Test for:
734 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
735 */
736 public void testForceRemoveActiveAdmin() throws Exception {
737 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
738
739 // Add admin.
740 setupPackageInPackageManager(admin1.getPackageName(),
741 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
742 /* appId= */ 10138,
743 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
744 dpm.setActiveAdmin(admin1, /* replace =*/ false);
745 assertTrue(dpm.isAdminActive(admin1));
746
747 // Calling from a non-shell uid should fail with a SecurityException
748 mContext.binder.callingUid = 123456;
749 assertExpectException(SecurityException.class,
750 /* messageRegex =*/ "Non-shell user attempted to call",
751 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
752
753 mContext.binder.callingUid = Process.SHELL_UID;
754 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
755
756 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
757 // Verify
758 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
759 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
760 null, DpmMockContext.CALLER_USER_HANDLE);
761 }
762
Makoto Onukib643fb02015-09-22 15:03:44 -0700763 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000764 * Test for: @{link DevicePolicyManager#setActivePasswordState}
765 *
766 * Validates that when the password for a user changes, the notification broadcast intent
767 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
768 * addition to ones in the original user.
769 */
770 public void testSetActivePasswordState_sendToProfiles() throws Exception {
771 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
772
773 final int MANAGED_PROFILE_USER_ID = 78;
774 final int MANAGED_PROFILE_ADMIN_UID =
775 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
776
777 // Setup device owner.
778 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
779 mContext.packageName = admin1.getPackageName();
780 setupDeviceOwner();
781
782 // Add a managed profile belonging to the system user.
783 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
784
785 // Change the parent user's password.
786 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
787
788 // Both the device owner and the managed profile owner should receive this broadcast.
789 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
790 intent.setComponent(admin1);
791 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
792
793 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
794 MockUtils.checkIntent(intent),
795 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
796 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
797 MockUtils.checkIntent(intent),
798 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
799 }
800
801 /**
802 * Test for: @{link DevicePolicyManager#setActivePasswordState}
803 *
804 * Validates that when the password for a managed profile changes, the notification broadcast
805 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
806 * its parent.
807 */
808 public void testSetActivePasswordState_notSentToParent() throws Exception {
809 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
810
811 final int MANAGED_PROFILE_USER_ID = 78;
812 final int MANAGED_PROFILE_ADMIN_UID =
813 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
814
815 // Setup device owner.
816 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
817 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100818 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000819 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
820 setupDeviceOwner();
821
822 // Add a managed profile belonging to the system user.
823 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
824
825 // Change the profile's password.
826 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
827
828 // Both the device owner and the managed profile owner should receive this broadcast.
829 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
830 intent.setComponent(admin1);
831 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
832
833 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
834 MockUtils.checkIntent(intent),
835 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
836 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
837 MockUtils.checkIntent(intent),
838 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
839 }
840 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000841 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700842 */
843 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000844 setDeviceOwner();
845
846 // Try to set a profile owner on the same user, which should fail.
847 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
848 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100849 assertExpectException(IllegalStateException.class,
850 /* messageRegex= */ "already has a device owner",
851 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000852
853 // DO admin can't be deactivated.
854 dpm.removeActiveAdmin(admin1);
855 assertTrue(dpm.isAdminActive(admin1));
856
857 // TODO Test getDeviceOwnerName() too. To do so, we need to change
858 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
859 }
860
861 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700862 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800863 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700864 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
865 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
866
Makoto Onukid932f762015-09-29 16:53:38 -0700867 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700868 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
869
Makoto Onukid932f762015-09-29 16:53:38 -0700870 // Make sure admin1 is installed on system user.
871 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700872
Makoto Onukic8a5a552015-11-19 14:29:12 -0800873 // Check various get APIs.
874 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
875
Makoto Onukib643fb02015-09-22 15:03:44 -0700876 // DO needs to be an DA.
877 dpm.setActiveAdmin(admin1, /* replace =*/ false);
878
879 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700880 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700881
Makoto Onukic8a5a552015-11-19 14:29:12 -0800882 // getDeviceOwnerComponent should return the admin1 component.
883 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
884 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
885
886 // Check various get APIs.
887 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
888
889 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
890 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
891 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
892 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
893
894 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
895
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000896 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100897 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000898 eq(admin1.getPackageName()));
899
Makoto Onukib643fb02015-09-22 15:03:44 -0700900 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100901 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700902 eq(UserHandle.USER_SYSTEM), eq(false));
903
904 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
905 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
906 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
907
Makoto Onukic8a5a552015-11-19 14:29:12 -0800908 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700909 }
910
Makoto Onukic8a5a552015-11-19 14:29:12 -0800911 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
912 final int origCallingUser = mContext.binder.callingUid;
913 final List origPermissions = new ArrayList(mContext.callerPermissions);
914 mContext.callerPermissions.clear();
915
916 mContext.callerPermissions.add(permission.MANAGE_USERS);
917
918 mContext.binder.callingUid = Process.SYSTEM_UID;
919
920 // TODO Test getDeviceOwnerName() too. To do so, we need to change
921 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
922 if (hasDeviceOwner) {
923 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
924 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
925 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
926
927 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
928 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
929 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
930 } else {
931 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
932 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
933 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
934
935 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
936 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
937 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
938 }
939
940 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
941 if (hasDeviceOwner) {
942 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
943 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
944 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
945
946 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
947 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
948 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
949 } else {
950 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
951 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
952 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
953
954 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
955 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
956 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
957 }
958
959 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
960 // Still with MANAGE_USERS.
961 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
962 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
963 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
964
965 if (hasDeviceOwner) {
966 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
967 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
968 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
969 } else {
970 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
971 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
972 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
973 }
974
975 mContext.binder.callingUid = Process.SYSTEM_UID;
976 mContext.callerPermissions.remove(permission.MANAGE_USERS);
977 // System can still call "OnAnyUser" without MANAGE_USERS.
978 if (hasDeviceOwner) {
979 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
980 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
981 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
982
983 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
984 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
985 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
986 } else {
987 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
988 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
989 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
990
991 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
992 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
993 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
994 }
995
996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
997 // Still no MANAGE_USERS.
998 if (hasDeviceOwner) {
999 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1000 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1001 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1002 } else {
1003 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1004 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1005 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1006 }
1007
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001008 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1009 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1010 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1011 dpm::getDeviceOwnerComponentOnAnyUser);
1012 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1013 dpm::getDeviceOwnerUserId);
1014 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1015 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001016
1017 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1018 // Still no MANAGE_USERS.
1019 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1020 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1021 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1022
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001023 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1024 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1025 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1026 dpm::getDeviceOwnerComponentOnAnyUser);
1027 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1028 dpm::getDeviceOwnerUserId);
1029 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1030 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001031
1032 // Restore.
1033 mContext.binder.callingUid = origCallingUser;
1034 mContext.callerPermissions.addAll(origPermissions);
1035 }
1036
1037
Makoto Onukib643fb02015-09-22 15:03:44 -07001038 /**
1039 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1040 */
1041 public void testSetDeviceOwner_noSuchPackage() {
1042 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001043 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1045 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1046
1047 // Call from a process on the system user.
1048 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1049
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001050 assertExpectException(IllegalArgumentException.class,
1051 /* messageRegex= */ "Invalid component",
1052 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001053 }
1054
1055 public void testSetDeviceOwner_failures() throws Exception {
1056 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1057 }
1058
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 public void testClearDeviceOwner() throws Exception {
1060 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001061 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001062 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1063 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1064
1065 // Set admin1 as a DA to the secondary user.
1066 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1067
1068 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1069
1070 // Set admin 1 as the DO to the system user.
1071
1072 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1073 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1074 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1075 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1076
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001077 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001078 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001079 eq(admin1.getPackageName()));
1080
Makoto Onukic8a5a552015-11-19 14:29:12 -08001081 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001082
Makoto Onuki90b89652016-01-28 14:44:18 -08001083 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001084 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001085 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001086
1087 assertTrue(dpm.isAdminActive(admin1));
1088 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1089
Makoto Onukia52562c2015-10-01 16:12:31 -07001090 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001092
1093 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001094 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1095 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001096
1097 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001098 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001099 assertExpectException(IllegalStateException.class,
1100 /* messageRegex= */ "User must be running and unlocked",
1101 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001102
Pavel Grafov75c0a892017-05-18 17:28:27 +01001103 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1104 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1106
1107 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001108 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001109
Pavel Grafov75c0a892017-05-18 17:28:27 +01001110 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001111 eq(false),
1112 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1113
Pavel Grafov75c0a892017-05-18 17:28:27 +01001114 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001115 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001116 eq(null),
1117 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001118
Sudheer Shanka101c3532018-01-08 16:28:42 -08001119 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1120 null, UserHandle.USER_SYSTEM);
1121
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001122 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001123
1124 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1125 // and once for clearing it.
1126 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1127 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1128 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001129 // TODO Check other calls.
1130 }
1131
1132 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1133 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001134 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1136 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1137
1138 // Set admin1 as a DA to the secondary user.
1139 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1140
1141 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1142
1143 // Set admin 1 as the DO to the system user.
1144
1145 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1146 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1147 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1148 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1149
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001150 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001151 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001152 eq(admin1.getPackageName()));
1153
Makoto Onukic8a5a552015-11-19 14:29:12 -08001154 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001155
1156 // Now call clear from the secondary user, which should throw.
1157 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1158
1159 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001160 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001161 eq(admin1.getPackageName()),
1162 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001163 assertExpectException(SecurityException.class,
1164 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1165 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001166
Makoto Onukic8a5a552015-11-19 14:29:12 -08001167 // DO shouldn't be removed.
1168 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001169 }
1170
Makoto Onukib643fb02015-09-22 15:03:44 -07001171 public void testSetProfileOwner() throws Exception {
1172 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001173
Makoto Onuki90b89652016-01-28 14:44:18 -08001174 // PO admin can't be deactivated.
1175 dpm.removeActiveAdmin(admin1);
1176 assertTrue(dpm.isAdminActive(admin1));
1177
Makoto Onuki803d6752015-10-30 12:58:39 -07001178 // Try setting DO on the same user, which should fail.
1179 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001180 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1181 runAsCaller(mServiceContext, dpms, dpm -> {
1182 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001183 assertExpectException(IllegalStateException.class,
1184 /* messageRegex= */ "already has a profile owner",
1185 () -> dpm.setDeviceOwner(admin2, "owner-name",
1186 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001187 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001188 }
1189
Makoto Onuki90b89652016-01-28 14:44:18 -08001190 public void testClearProfileOwner() throws Exception {
1191 setAsProfileOwner(admin1);
1192
1193 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1194
1195 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1196 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1197
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001198 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001199 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001200 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001201 assertExpectException(IllegalStateException.class,
1202 /* messageRegex= */ "User must be running and unlocked",
1203 () -> dpm.clearProfileOwner(admin1));
1204
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001205 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001206 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001207 dpm.clearProfileOwner(admin1);
1208
1209 // Check
1210 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001211 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001212 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1213 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001214 }
1215
Makoto Onukib643fb02015-09-22 15:03:44 -07001216 public void testSetProfileOwner_failures() throws Exception {
1217 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1218 }
1219
Makoto Onukia52562c2015-10-01 16:12:31 -07001220 public void testGetDeviceOwnerAdminLocked() throws Exception {
1221 checkDeviceOwnerWithMultipleDeviceAdmins();
1222 }
1223
1224 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1225 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1226 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1227 // make sure it gets the right component from the right user.
1228
1229 final int ANOTHER_USER_ID = 100;
1230 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1231
Pavel Grafov75c0a892017-05-18 17:28:27 +01001232 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001233
1234 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001235 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001236 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1237 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1238
1239 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1240
Pavel Grafov75c0a892017-05-18 17:28:27 +01001241 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001242
Makoto Onukia52562c2015-10-01 16:12:31 -07001243 // Make sure the admin packge is installed to each user.
1244 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1245 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1246
1247 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1248 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1249
1250 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1251
1252
1253 // Set active admins to the users.
1254 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1255 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1256
1257 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1258 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1259
1260 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1261
1262 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001263 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001264 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1265
Makoto Onukic8a5a552015-11-19 14:29:12 -08001266 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001267
1268 // Then check getDeviceOwnerAdminLocked().
1269 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1270 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1271 }
1272
1273 /**
1274 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001275 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1276 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001277 *
1278 * We didn't use to persist the DO component class name, but now we do, and the above method
1279 * finds the right component from a package name upon migration.
1280 */
1281 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001282 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001283 checkDeviceOwnerWithMultipleDeviceAdmins();
1284
1285 // Overwrite the device owner setting and clears the clas name.
1286 dpms.mOwners.setDeviceOwner(
1287 new ComponentName(admin2.getPackageName(), ""),
1288 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1289 dpms.mOwners.writeDeviceOwner();
1290
1291 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001292 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001293
1294 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001295 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001296 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001297 initializeDpms();
1298
1299 // Now the DO component name is a full name.
1300 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1301 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001302 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001303 }
1304
Makoto Onukib643fb02015-09-22 15:03:44 -07001305 public void testSetGetApplicationRestriction() {
1306 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001307 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001308
1309 {
1310 Bundle rest = new Bundle();
1311 rest.putString("KEY_STRING", "Foo1");
1312 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1313 }
1314
1315 {
1316 Bundle rest = new Bundle();
1317 rest.putString("KEY_STRING", "Foo2");
1318 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1319 }
1320
1321 {
1322 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1323 assertNotNull(returned);
1324 assertEquals(returned.size(), 1);
1325 assertEquals(returned.get("KEY_STRING"), "Foo1");
1326 }
1327
1328 {
1329 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1330 assertNotNull(returned);
1331 assertEquals(returned.size(), 1);
1332 assertEquals(returned.get("KEY_STRING"), "Foo2");
1333 }
1334
1335 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1336 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1337 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001338
Edman Anjosf9946772016-11-28 16:35:15 +01001339 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001340 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1341 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001342 *
1343 * @param packageName the name of the package to be setup
1344 * @param appId the application ID to be given to the package
1345 * @return the UID of the package as known by the mock package manager
1346 */
1347 private int setupPackageInPackageManager(final String packageName, final int appId)
1348 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001349 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001350 ApplicationInfo.FLAG_HAS_CODE);
1351 }
1352
1353 /**
1354 * Setup a package in the package manager mock. Useful for faking installed applications.
1355 *
1356 * @param packageName the name of the package to be setup
1357 * @param userId the user id where the package will be "installed"
1358 * @param appId the application ID to be given to the package
1359 * @param flags flags to set in the ApplicationInfo for this package
1360 * @return the UID of the package as known by the mock package manager
1361 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001362 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1363 int flags) throws Exception {
1364 final int uid = UserHandle.getUid(userId, appId);
1365 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001366 final PackageInfo pi = new PackageInfo();
1367 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001368 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001369 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001370 eq(packageName),
1371 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001372 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001373 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001374 eq(packageName),
1375 anyInt(),
1376 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001377 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001378 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001379 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001380 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001381 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001382 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001383 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001384 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001385 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001386 return uid;
1387 }
1388
Robin Lee7f5c91c2017-02-08 21:27:02 +00001389 public void testCertificateDisclosure() throws Exception {
1390 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1391 final UserHandle user = UserHandle.of(userId);
1392
1393 mContext.applicationInfo = new ApplicationInfo();
1394 mContext.callerPermissions.add(permission.MANAGE_USERS);
1395 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001396 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001397 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1398
Robin Leeabaa0692017-02-20 20:54:22 +00001399 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1400 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001401
1402 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1403 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1404
1405 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001406 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001407 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001408 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001409 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001410 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001411 .cancelAsUser(anyString(), anyInt(), eq(user));
1412
1413 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001414 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001415 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001416 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1417 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001418 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001419 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001420 .notifyAsUser(anyString(), anyInt(), argThat(
1421 new BaseMatcher<Notification>() {
1422 @Override
1423 public boolean matches(Object item) {
1424 final Notification noti = (Notification) item;
1425 return TEST_STRING.equals(
1426 noti.extras.getString(Notification.EXTRA_TITLE));
1427 }
1428 @Override
1429 public void describeTo(Description description) {
1430 description.appendText(
1431 "Notification{title=\"" + TEST_STRING + "\"}");
1432 }
1433 }), eq(user));
1434 }
1435
Edman Anjosf9946772016-11-28 16:35:15 +01001436 /**
1437 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1438 * privileges can acually be exercised by a delegate are not covered here.
1439 */
1440 public void testDelegation() throws Exception {
1441 setAsProfileOwner(admin1);
1442
1443 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1444
1445 // Given two packages
1446 final String CERT_DELEGATE = "com.delegate.certs";
1447 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1448 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1449 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1450 20989);
1451
1452 // On delegation
1453 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1454 mContext.packageName = admin1.getPackageName();
1455 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1456 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1457
1458 // DPMS correctly stores and retrieves the delegates
1459 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1460 assertEquals(2, policy.mDelegationMap.size());
1461 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1462 DELEGATION_CERT_INSTALL);
1463 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1464 DELEGATION_CERT_INSTALL);
1465 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1466 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1467 DELEGATION_APP_RESTRICTIONS);
1468 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1469 DELEGATION_APP_RESTRICTIONS);
1470 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1471
1472 // On calling install certificate APIs from an unauthorized process
1473 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1474 mContext.packageName = RESTRICTIONS_DELEGATE;
1475
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001476 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1477 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001478
1479 // On calling install certificate APIs from an authorized process
1480 mContext.binder.callingUid = CERT_DELEGATE_UID;
1481 mContext.packageName = CERT_DELEGATE;
1482
1483 // DPMS executes without a SecurityException
1484 try {
1485 dpm.installCaCert(null, null);
1486 } catch (SecurityException unexpected) {
1487 fail("Threw SecurityException on authorized access");
1488 } catch (NullPointerException expected) {
1489 }
1490
1491 // On removing a delegate
1492 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1493 mContext.packageName = admin1.getPackageName();
1494 dpm.setCertInstallerPackage(admin1, null);
1495
1496 // DPMS does not allow access to ex-delegate
1497 mContext.binder.callingUid = CERT_DELEGATE_UID;
1498 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001499 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1500 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001501
1502 // But still allows access to other existing delegates
1503 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1504 mContext.packageName = RESTRICTIONS_DELEGATE;
1505 try {
1506 dpm.getApplicationRestrictions(null, "pkg");
1507 } catch (SecurityException expected) {
1508 fail("Threw SecurityException on authorized access");
1509 }
1510 }
1511
Esteban Talaverabf60f722015-12-10 16:26:44 +00001512 public void testApplicationRestrictionsManagingApp() throws Exception {
1513 setAsProfileOwner(admin1);
1514
Rubin Xued1928a2016-02-11 17:23:06 +00001515 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001516 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001517 final String nonDelegateExceptionMessageRegex =
1518 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001520 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1521 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001522
Esteban Talaverabf60f722015-12-10 16:26:44 +00001523 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1524 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001525 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1526 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001527 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001528 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001529 rest.putString("KEY_STRING", "Foo1");
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 // Check via the profile owner that no restrictions were set.
1534 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001535 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001536 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1537
Rubin Xued1928a2016-02-11 17:23:06 +00001538 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001539 assertExpectException(PackageManager.NameNotFoundException.class,
1540 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1541 () -> dpm.setApplicationRestrictionsManagingPackage(
1542 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001543
Esteban Talaverabf60f722015-12-10 16:26:44 +00001544 // Let appRestrictionsManagerPackage manage app restrictions
1545 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1546 assertEquals(appRestrictionsManagerPackage,
1547 dpm.getApplicationRestrictionsManagingPackage(admin1));
1548
1549 // Now that package should be able to set and retrieve app restrictions.
1550 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001551 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001552 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1553 dpm.setApplicationRestrictions(null, "pkg1", rest);
1554 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1555 assertEquals(1, returned.size(), 1);
1556 assertEquals("Foo1", returned.get("KEY_STRING"));
1557
1558 // The same app running on a separate user shouldn't be able to manage app restrictions.
1559 mContext.binder.callingUid = UserHandle.getUid(
1560 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1561 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001562 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1563 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001564
1565 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1566 // too.
1567 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001568 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001569 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1570 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1571 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1572
1573 // Removing the ability for the package to manage app restrictions.
1574 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1575 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1576 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001577 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001578 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001579 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1580 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001581 }
1582
Makoto Onukia4f11972015-10-01 13:19:58 -07001583 public void testSetUserRestriction_asDo() throws Exception {
1584 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001585 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001586 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1587 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1588
1589 // First, set DO.
1590
1591 // Call from a process on the system user.
1592 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1593
1594 // Make sure admin1 is installed on system user.
1595 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001596
1597 // Call.
1598 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001599 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001600 UserHandle.USER_SYSTEM));
1601
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001602 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001603 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001604 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001605 DpmTestUtils.assertRestrictions(
1606 DpmTestUtils.newRestrictions(defaultRestrictions),
1607 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1608 );
1609 DpmTestUtils.assertRestrictions(
1610 DpmTestUtils.newRestrictions(defaultRestrictions),
1611 dpm.getUserRestrictions(admin1)
1612 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001613 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001614 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001615 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001616 eq(true) /* isDeviceOwner */,
1617 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001618 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001619 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001620
1621 for (String restriction : defaultRestrictions) {
1622 dpm.clearUserRestriction(admin1, restriction);
1623 }
1624
Esteban Talavera548a04b2016-12-20 15:22:30 +00001625 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001627
1628 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001631 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1632 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001633 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634
Makoto Onukia4f11972015-10-01 13:19:58 -07001635 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001636 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001638 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1639 UserManager.DISALLOW_ADD_USER),
1640 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001641 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001642
Makoto Onuki068c54a2015-10-13 14:34:03 -07001643 DpmTestUtils.assertRestrictions(
1644 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001645 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001646 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1647 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001648 DpmTestUtils.assertRestrictions(
1649 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001651 dpm.getUserRestrictions(admin1)
1652 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001653
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001654 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001655 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001656 eq(UserHandle.USER_SYSTEM),
1657 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001658 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001659 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001660
Makoto Onuki068c54a2015-10-13 14:34:03 -07001661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1663 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1664 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001665 DpmTestUtils.assertRestrictions(
1666 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1667 dpm.getUserRestrictions(admin1)
1668 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001669
1670 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001672 eq(UserHandle.USER_SYSTEM),
1673 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001674 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001675 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001676
Esteban Talavera548a04b2016-12-20 15:22:30 +00001677 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001678
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1680 // DO sets them, the scope is global.
1681 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001682 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001684 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001687 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1688 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001689 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001690
1691 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1692 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001693 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694
1695 // More tests.
1696 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
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 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1700 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001701 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702
1703 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001707 UserManager.DISALLOW_ADD_USER),
1708 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710
1711 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001712 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713 eq(UserHandle.USER_SYSTEM),
1714 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001716 UserManager.DISALLOW_ADD_USER),
1717 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001718 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001719 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720
Eric Sandnessca5969d2018-08-10 13:28:46 +01001721 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1722 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1723 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724
Eric Sandnessca5969d2018-08-10 13:28:46 +01001725 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1726 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727
Eric Sandnessca5969d2018-08-10 13:28:46 +01001728 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1729 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1730 () -> dpm.setCameraDisabled(admin1, true));
1731 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1732
1733 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1734 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1735 () -> dpm.setKeyguardDisabledFeatures(admin1,
1736 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1737 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1738
1739 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1740 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1741 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1742 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1743
1744 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1745 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1746 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1747 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001748 }
1749
1750 public void testSetUserRestriction_asPo() {
1751 setAsProfileOwner(admin1);
1752
Makoto Onuki068c54a2015-10-13 14:34:03 -07001753 DpmTestUtils.assertRestrictions(
1754 DpmTestUtils.newRestrictions(),
1755 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1756 .ensureUserRestrictions()
1757 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001758
1759 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001760 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001761 eq(DpmMockContext.CALLER_USER_HANDLE),
1762 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001763 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001764 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765
Makoto Onukia4f11972015-10-01 13:19:58 -07001766 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 eq(DpmMockContext.CALLER_USER_HANDLE),
1769 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1770 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001771 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001773
Makoto Onuki068c54a2015-10-13 14:34:03 -07001774 DpmTestUtils.assertRestrictions(
1775 DpmTestUtils.newRestrictions(
1776 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1777 UserManager.DISALLOW_OUTGOING_CALLS
1778 ),
1779 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1780 .ensureUserRestrictions()
1781 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001782 DpmTestUtils.assertRestrictions(
1783 DpmTestUtils.newRestrictions(
1784 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1785 UserManager.DISALLOW_OUTGOING_CALLS
1786 ),
1787 dpm.getUserRestrictions(admin1)
1788 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001789
1790 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001791 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001792 eq(DpmMockContext.CALLER_USER_HANDLE),
1793 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
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 Onuki068c54a2015-10-13 14:34:03 -07001796
1797 DpmTestUtils.assertRestrictions(
1798 DpmTestUtils.newRestrictions(
1799 UserManager.DISALLOW_OUTGOING_CALLS
1800 ),
1801 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1802 .ensureUserRestrictions()
1803 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001804 DpmTestUtils.assertRestrictions(
1805 DpmTestUtils.newRestrictions(
1806 UserManager.DISALLOW_OUTGOING_CALLS
1807 ),
1808 dpm.getUserRestrictions(admin1)
1809 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001810
1811 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001812 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001813 eq(DpmMockContext.CALLER_USER_HANDLE),
1814 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001815 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001816 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001817
Makoto Onuki068c54a2015-10-13 14:34:03 -07001818 DpmTestUtils.assertRestrictions(
1819 DpmTestUtils.newRestrictions(),
1820 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1821 .ensureUserRestrictions()
1822 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001823 DpmTestUtils.assertRestrictions(
1824 DpmTestUtils.newRestrictions(),
1825 dpm.getUserRestrictions(admin1)
1826 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001827
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1829 // though when DO sets them they'll be applied globally.
1830 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001831 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001832 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001833 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001834 eq(DpmMockContext.CALLER_USER_HANDLE),
1835 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1836 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001837 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001838 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001839
1840 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001841 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001842 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001843 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001845 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001846 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847
Makoto Onukia4f11972015-10-01 13:19:58 -07001848 // TODO Make sure restrictions are written to the file.
1849 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001850
Esteban Talavera548a04b2016-12-20 15:22:30 +00001851
1852 public void testDefaultEnabledUserRestrictions() throws Exception {
1853 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1854 mContext.callerPermissions.add(permission.MANAGE_USERS);
1855 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1856 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1857
1858 // First, set DO.
1859
1860 // Call from a process on the system user.
1861 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1862
1863 // Make sure admin1 is installed on system user.
1864 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1865
1866 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1867 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1868 UserHandle.USER_SYSTEM));
1869
1870 // Check that the user restrictions that are enabled by default are set. Then unset them.
1871 String[] defaultRestrictions = UserRestrictionsUtils
1872 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1873 assertTrue(defaultRestrictions.length > 0);
1874 DpmTestUtils.assertRestrictions(
1875 DpmTestUtils.newRestrictions(defaultRestrictions),
1876 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1877 );
1878 DpmTestUtils.assertRestrictions(
1879 DpmTestUtils.newRestrictions(defaultRestrictions),
1880 dpm.getUserRestrictions(admin1)
1881 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001883 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001884 MockUtils.checkUserRestrictions(defaultRestrictions),
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 for (String restriction : defaultRestrictions) {
1891 dpm.clearUserRestriction(admin1, restriction);
1892 }
1893
1894 assertNoDeviceOwnerRestrictions();
1895
1896 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001897 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001898 initializeDpms();
1899 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1900 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1901
1902 assertNoDeviceOwnerRestrictions();
1903
1904 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1905 // is set as it wasn't enabled during setDeviceOwner.
1906 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1907 assertFalse(UserRestrictionsUtils
1908 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1909 UserRestrictionsUtils
1910 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1911 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001912 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001913 initializeDpms();
1914 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1915 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1916
1917 DpmTestUtils.assertRestrictions(
1918 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1919 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1920 );
1921 DpmTestUtils.assertRestrictions(
1922 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1923 dpm.getUserRestrictions(admin1)
1924 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001925 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001926 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001927 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001928 eq(true) /* isDeviceOwner */,
1929 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001930 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001931 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001932
1933 // Remove the restriction.
1934 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1935
1936 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1937 initializeDpms();
1938 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1939 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1940 assertNoDeviceOwnerRestrictions();
1941 } finally {
1942 UserRestrictionsUtils
1943 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1944 }
1945 }
1946
1947 private void assertNoDeviceOwnerRestrictions() {
1948 DpmTestUtils.assertRestrictions(
1949 DpmTestUtils.newRestrictions(),
1950 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1951 );
1952 DpmTestUtils.assertRestrictions(
1953 DpmTestUtils.newRestrictions(),
1954 dpm.getUserRestrictions(admin1)
1955 );
1956 }
1957
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001958 public void testGetMacAddress() throws Exception {
1959 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1960 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1961 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1962
1963 // In this test, change the caller user to "system".
1964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1965
1966 // Make sure admin1 is installed on system user.
1967 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1968
1969 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001970 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1971 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001972
1973 // DO needs to be an DA.
1974 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1975 assertTrue(dpm.isAdminActive(admin1));
1976
1977 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001978 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1979 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001980
1981 // Test 3. Caller has PO, but not DO.
1982 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001983 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1984 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001985
1986 // Remove PO.
1987 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001988 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001989 // Test 4, Caller is DO now.
1990 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1991
1992 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001993 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001994
1995 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001996 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001997 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001998
1999 // 4-3. With a real MAC address.
2000 final WifiInfo wi = new WifiInfo();
2001 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01002002 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002003 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002004 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002005
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002006 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002007 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2008 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2009
2010 // In this test, change the caller user to "system".
2011 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2012
2013 // Make sure admin1 is installed on system user.
2014 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2015
2016 // Set admin1 as DA.
2017 dpm.setActiveAdmin(admin1, false);
2018 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002019 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2020 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002021
2022 // Set admin1 as PO.
2023 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002024 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2025 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002026
2027 // Remove PO and add DO.
2028 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002029 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002030 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2031
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002032 // admin1 is DO.
2033 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002034 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002035 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002036 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2037 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002038
2039 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002040 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002041 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002042 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2043 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002044
2045 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002046 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002047 dpm.reboot(admin1);
2048 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002049
2050 public void testSetGetSupportText() {
2051 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2052 dpm.setActiveAdmin(admin1, true);
2053 dpm.setActiveAdmin(admin2, true);
2054 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2055
2056 // Null default support messages.
2057 {
2058 assertNull(dpm.getLongSupportMessage(admin1));
2059 assertNull(dpm.getShortSupportMessage(admin1));
2060 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2061 assertNull(dpm.getShortSupportMessageForUser(admin1,
2062 DpmMockContext.CALLER_USER_HANDLE));
2063 assertNull(dpm.getLongSupportMessageForUser(admin1,
2064 DpmMockContext.CALLER_USER_HANDLE));
2065 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2066 }
2067
2068 // Only system can call the per user versions.
2069 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002070 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2071 () -> dpm.getShortSupportMessageForUser(admin1,
2072 DpmMockContext.CALLER_USER_HANDLE));
2073 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2074 () -> dpm.getLongSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002076 }
2077
2078 // Can't set message for admin in another uid.
2079 {
2080 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002081 assertExpectException(SecurityException.class,
2082 /* messageRegex= */ "is not owned by uid",
2083 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002084 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2085 }
2086
2087 // Set/Get short returns what it sets and other admins text isn't changed.
2088 {
2089 final String supportText = "Some text to test with.";
2090 dpm.setShortSupportMessage(admin1, supportText);
2091 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2092 assertNull(dpm.getLongSupportMessage(admin1));
2093 assertNull(dpm.getShortSupportMessage(admin2));
2094
2095 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2096 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2097 DpmMockContext.CALLER_USER_HANDLE));
2098 assertNull(dpm.getShortSupportMessageForUser(admin2,
2099 DpmMockContext.CALLER_USER_HANDLE));
2100 assertNull(dpm.getLongSupportMessageForUser(admin1,
2101 DpmMockContext.CALLER_USER_HANDLE));
2102 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2103
2104 dpm.setShortSupportMessage(admin1, null);
2105 assertNull(dpm.getShortSupportMessage(admin1));
2106 }
2107
2108 // Set/Get long returns what it sets and other admins text isn't changed.
2109 {
2110 final String supportText = "Some text to test with.\nWith more text.";
2111 dpm.setLongSupportMessage(admin1, supportText);
2112 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2113 assertNull(dpm.getShortSupportMessage(admin1));
2114 assertNull(dpm.getLongSupportMessage(admin2));
2115
2116 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2117 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2118 DpmMockContext.CALLER_USER_HANDLE));
2119 assertNull(dpm.getLongSupportMessageForUser(admin2,
2120 DpmMockContext.CALLER_USER_HANDLE));
2121 assertNull(dpm.getShortSupportMessageForUser(admin1,
2122 DpmMockContext.CALLER_USER_HANDLE));
2123 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2124
2125 dpm.setLongSupportMessage(admin1, null);
2126 assertNull(dpm.getLongSupportMessage(admin1));
2127 }
2128 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002129
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002130 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002131 setAsProfileOwner(admin1);
2132
2133 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002134 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002135
2136 // Setup
2137 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2138 final String package1 = "com.example.one";
2139 final String package2 = "com.example.two";
2140 pkgsToRestrict.add(package1);
2141 pkgsToRestrict.add(package2);
2142 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2143 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002144 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002145
2146 // Verify
2147 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002148 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002149 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2150 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2151 eq(DpmMockContext.CALLER_USER_HANDLE));
2152
2153 // Setup
2154 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002155 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002156
2157 // Verify
2158 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002159 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002160 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2161 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2162 eq(DpmMockContext.CALLER_USER_HANDLE));
2163 }
2164
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002165 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002166 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2167 dpm.setActiveAdmin(admin1, true);
2168 assertTrue(dpm.isAdminActive(admin1));
2169 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2170
2171 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002172 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002173 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002174 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002175 }
2176
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002177 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002178 setAsProfileOwner(admin1);
2179
2180 // Setup
2181 final ArrayList<String> emptyList = new ArrayList<>();
2182 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2183 final String package1 = "com.example.one";
2184 final String package2 = "com.example.two";
2185 final String package3 = "com.example.three";
2186 pkgsToRestrict.add(package1);
2187 pkgsToRestrict.add(package2);
2188 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2189 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002190 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002191
2192 // Verify
2193 assertEquals(emptyList, excludedPkgs);
2194 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2195 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002196 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002197 DpmMockContext.CALLER_USER_HANDLE));
2198 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002199 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002200 DpmMockContext.CALLER_USER_HANDLE));
2201 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002203 DpmMockContext.CALLER_USER_HANDLE));
2204 }
2205
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002206 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002207 setAsProfileOwner(admin1);
2208 assertExpectException(SecurityException.class,
2209 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002210 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002211 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2212 dpm.clearProfileOwner(admin1);
2213
2214 setDeviceOwner();
2215 assertExpectException(SecurityException.class,
2216 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002217 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002218 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2219 clearDeviceOwner();
2220 }
2221
phweiss73145f42017-01-17 19:06:38 +01002222 public void testCreateAdminSupportIntent() throws Exception {
2223 // Setup device owner.
2224 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2225 setupDeviceOwner();
2226
2227 // Nonexisting permission returns null
2228 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2229 assertNull(intent);
2230
2231 // Existing permission that is not set returns null
2232 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2233 assertNull(intent);
2234
2235 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002236 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002237 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2238 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2239 .thenReturn(true);
2240 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2241 assertNull(intent);
2242
2243 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002244 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002245 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2246 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2247 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2248 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2249 assertNotNull(intent);
2250 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2251 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2252 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002253 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002254 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2255 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2256
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002257 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2258 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002259
2260 // Camera is not disabled
2261 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2262 assertNull(intent);
2263
2264 // Camera is disabled
2265 dpm.setCameraDisabled(admin1, true);
2266 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2267 assertNotNull(intent);
2268 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2269 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2270
2271 // Screen capture is not disabled
2272 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2273 assertNull(intent);
2274
2275 // Screen capture is disabled
2276 dpm.setScreenCaptureDisabled(admin1, true);
2277 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2278 assertNotNull(intent);
2279 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2280 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2281
2282 // Same checks for different user
2283 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2284 // Camera should be disabled by device owner
2285 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2286 assertNotNull(intent);
2287 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2288 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2289 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2290 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2291 // ScreenCapture should not be disabled by device owner
2292 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2293 assertNull(intent);
2294 }
2295
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002296 /**
2297 * Test for:
2298 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002299 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002300 * {@link DevicePolicyManager#isAffiliatedUser}
2301 */
2302 public void testUserAffiliation() throws Exception {
2303 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2304 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2305 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2306
2307 // Check that the system user is unaffiliated.
2308 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2309 assertFalse(dpm.isAffiliatedUser());
2310
2311 // Set a device owner on the system user. Check that the system user becomes affiliated.
2312 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2313 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2314 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2315 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002316 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002317
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002318 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002319 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2320 setAsProfileOwner(admin2);
2321 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002322 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002323
2324 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2325 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002326 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002327 userAffiliationIds.add("red");
2328 userAffiliationIds.add("green");
2329 userAffiliationIds.add("blue");
2330 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002331 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002332 assertFalse(dpm.isAffiliatedUser());
2333
2334 // Have the device owner specify a set of affiliation ids that do not intersect with those
2335 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002336 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002337 deviceAffiliationIds.add("cyan");
2338 deviceAffiliationIds.add("yellow");
2339 deviceAffiliationIds.add("magenta");
2340 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2341 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002342 MoreAsserts.assertContentsInAnyOrder(
2343 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002344 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2345 assertFalse(dpm.isAffiliatedUser());
2346
2347 // Have the profile owner specify a set of affiliation ids that intersect with those
2348 // specified by the device owner. Check that the test user becomes affiliated.
2349 userAffiliationIds.add("yellow");
2350 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002351 MoreAsserts.assertContentsInAnyOrder(
2352 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002353 assertTrue(dpm.isAffiliatedUser());
2354
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002355 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002356 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002357 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002358 assertFalse(dpm.isAffiliatedUser());
2359
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002360 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2361 dpm.setAffiliationIds(admin2, userAffiliationIds);
2362 assertTrue(dpm.isAffiliatedUser());
2363 dpm.clearProfileOwner(admin2);
2364 assertFalse(dpm.isAffiliatedUser());
2365
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002366 // Check that the system user remains affiliated.
2367 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2368 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002369
2370 // Clear the device owner - the user becomes unaffiliated.
2371 clearDeviceOwner();
2372 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002373 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002374
2375 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002376 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002377 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2378 }
2379
2380 public void testSetUserProvisioningState_permission() throws Exception {
2381 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002382
2383 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2384 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2385 }
2386
2387 public void testSetUserProvisioningState_unprivileged() throws Exception {
2388 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002389 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2390 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2391 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002392 }
2393
2394 public void testSetUserProvisioningState_noManagement() {
2395 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002396 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002397 assertExpectException(IllegalStateException.class,
2398 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2399 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2400 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002401 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2402 }
2403
2404 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2405 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2406 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002407
2408 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2409 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2410 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2411 }
2412
2413 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2414 throws Exception {
2415 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2416 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002417
2418 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2419 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2420 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2421 }
2422
2423 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2424 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2425 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002426
2427 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2428 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2429 }
2430
2431 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2432 throws Exception {
2433 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002434
2435 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2436 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2437 DevicePolicyManager.STATE_USER_UNMANAGED);
2438 }
2439
2440 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2441 throws Exception {
2442 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002443
2444 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2445 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2446 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2447 }
2448
2449 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2450 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002451
2452 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2453 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2454 }
2455
2456 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2457 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002458
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002459 assertExpectException(IllegalStateException.class,
2460 /* messageRegex= */ "Cannot move to user provisioning state",
2461 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2462 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2463 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002464 }
2465
2466 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2467 throws Exception {
2468 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002469
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002470 assertExpectException(IllegalStateException.class,
2471 /* messageRegex= */ "Cannot move to user provisioning state",
2472 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2473 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2474 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002475 }
2476
2477 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002478 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2479 mContext.callerPermissions.add(permission.MANAGE_USERS);
2480
Alan Treadwayafad8782016-01-19 15:15:08 +00002481 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2482 for (int state : states) {
2483 dpm.setUserProvisioningState(state, userId);
2484 assertEquals(state, dpm.getUserProvisioningState());
2485 }
2486 }
2487
2488 private void setupProfileOwner() throws Exception {
2489 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2490
2491 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2492 dpm.setActiveAdmin(admin1, false);
2493 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2494
2495 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2496 }
2497
2498 private void setupDeviceOwner() throws Exception {
2499 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2500
2501 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2502 dpm.setActiveAdmin(admin1, false);
2503 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2504
2505 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2506 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002507
2508 public void testSetMaximumTimeToLock() {
2509 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2510
2511 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2512 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2513
Pavel Grafov75c0a892017-05-18 17:28:27 +01002514 reset(getServices().powerManagerInternal);
2515 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002516
2517 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002518 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2519 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002520 reset(getServices().powerManagerInternal);
2521 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002522
2523 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002524 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2525 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002526 reset(getServices().powerManagerInternal);
2527 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002528
2529 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002530 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2531 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002532 reset(getServices().powerManagerInternal);
2533 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002534
2535 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002536 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2537 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002538 reset(getServices().powerManagerInternal);
2539 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002540
2541 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002542 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2543 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002544 reset(getServices().powerManagerInternal);
2545 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002546
2547 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002548 reset(getServices().powerManagerInternal);
2549 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002550
Pavel Grafov28939982017-10-03 15:11:52 +01002551 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2552 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2553 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002554 reset(getServices().powerManagerInternal);
2555 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002556
2557 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002558 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2559 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002560 reset(getServices().powerManagerInternal);
2561 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002562
Pavel Grafov28939982017-10-03 15:11:52 +01002563 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002564 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002565 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2566 verifyStayOnWhilePluggedCleared(false);
2567 }
2568
2569 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2570 // uses separate challenge.
2571 public void testSetMaximumTimeToLockProfile() throws Exception {
2572 final int PROFILE_USER = 15;
2573 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2574 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2575 mContext.binder.callingUid = PROFILE_ADMIN;
2576 final DevicePolicyManagerInternal dpmi =
2577 LocalServices.getService(DevicePolicyManagerInternal.class);
2578
2579 dpm.setMaximumTimeToLock(admin1, 0);
2580
2581 reset(getServices().powerManagerInternal);
2582 reset(getServices().settings);
2583
2584 // First add timeout for the profile.
2585 dpm.setMaximumTimeToLock(admin1, 10);
2586 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2587
2588 reset(getServices().powerManagerInternal);
2589 reset(getServices().settings);
2590
2591 // Add separate challenge
2592 when(getServices().lockPatternUtils
2593 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2594 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2595
2596 verifyScreenTimeoutCall(10L, PROFILE_USER);
2597 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2598
2599 reset(getServices().powerManagerInternal);
2600 reset(getServices().settings);
2601
2602 // Remove the timeout.
2603 dpm.setMaximumTimeToLock(admin1, 0);
2604 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2605 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2606
2607 reset(getServices().powerManagerInternal);
2608 reset(getServices().settings);
2609
2610 // Add it back.
2611 dpm.setMaximumTimeToLock(admin1, 10);
2612 verifyScreenTimeoutCall(10L, PROFILE_USER);
2613 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2614
2615 reset(getServices().powerManagerInternal);
2616 reset(getServices().settings);
2617
2618 // Remove separate challenge.
2619 reset(getServices().lockPatternUtils);
2620 when(getServices().lockPatternUtils
2621 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2622 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2623
2624 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2625 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2626
2627 reset(getServices().powerManagerInternal);
2628 reset(getServices().settings);
2629
2630 // Remove the timeout.
2631 dpm.setMaximumTimeToLock(admin1, 0);
2632 verifyScreenTimeoutCall(null, PROFILE_USER);
2633 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002634 }
2635
Michal Karpinski943aabd2016-10-06 11:09:25 +01002636 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2637 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2638 setupDeviceOwner();
2639 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2640
Michal Karpinskid084ca52017-01-18 15:54:18 +00002641 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2642 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2643 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2644 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2645 - ONE_MINUTE;
2646
2647 // verify that the minimum timeout cannot be modified on user builds (system property is
2648 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002649 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002650
2651 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2652 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2653 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2654
Pavel Grafov75c0a892017-05-18 17:28:27 +01002655 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002656
2657 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002658 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002659
Michal Karpinskid084ca52017-01-18 15:54:18 +00002660 // reset to default (0 means the admin is not participating, so default should be returned)
2661 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002662
2663 // aggregation should be the default if unset by any admin
2664 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2665 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2666
2667 // admin not participating by default
2668 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2669
2670 //clamping from the top
2671 dpm.setRequiredStrongAuthTimeout(admin1,
2672 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2673 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2674 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2675 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2676 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2677
Michal Karpinskid084ca52017-01-18 15:54:18 +00002678 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002679 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2680 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2681 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2682 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2683
2684 // clamping from the bottom
2685 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2686 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2687 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2688
Michal Karpinskid084ca52017-01-18 15:54:18 +00002689 // values within range
2690 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2691 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2692 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2693
2694 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2696 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002697
2698 // reset to default
2699 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2700 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2701 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2702 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2703
2704 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002705 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2706 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002707 }
2708
Pavel Grafov28939982017-10-03 15:11:52 +01002709 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002710 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002711 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002712 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002713 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002714 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002715 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002716 }
Pavel Grafov28939982017-10-03 15:11:52 +01002717 }
2718
2719 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002720 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2721 // UnfinishedVerificationException.
2722 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002723
Esteban Talavera01576862016-12-15 11:16:44 +00002724 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002725 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002726 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002727 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002728 .thenReturn(false);
2729 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002730 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2731 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002732 .thenReturn(true);
2733 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2734
2735 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002736 }
Victor Chang3e794af2016-03-04 13:48:17 +00002737
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002738 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2739 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002740 mContext.packageName = admin1.getPackageName();
2741 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2743 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2744 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2745 false);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2747 }
2748
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002749 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2750 setup_DeviceAdminFeatureOff();
2751 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2752 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2753 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2754 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2755 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2756 assertCheckProvisioningPreCondition(
2757 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2758 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2759 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2760 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2761 }
2762
Esteban Talavera01576862016-12-15 11:16:44 +00002763 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002764 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002765 .thenReturn(false);
2766 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002767 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2768 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002769 .thenReturn(true);
2770 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2771
2772 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002773 }
Victor Chang3e794af2016-03-04 13:48:17 +00002774
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002775 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2776 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002777 mContext.packageName = admin1.getPackageName();
2778 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2780 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2781 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2782 false);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2784
2785 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002786 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2790 true);
2791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2792 }
2793
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002794 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2795 setup_ManagedProfileFeatureOff();
2796 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2797 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2798 DevicePolicyManager.CODE_OK);
2799 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2800 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2801 assertCheckProvisioningPreCondition(
2802 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2803 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2804 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2805 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2806
2807 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002808 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002809 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2810 DevicePolicyManager.CODE_OK);
2811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2812 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2813 assertCheckProvisioningPreCondition(
2814 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2815 DevicePolicyManager.CODE_OK);
2816 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2817 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2818 }
2819
Esteban Talavera01576862016-12-15 11:16:44 +00002820 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002821 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002822 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002823 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2824 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002825 .thenReturn(true);
2826 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2827
2828 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002829 }
Victor Chang3e794af2016-03-04 13:48:17 +00002830
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002831 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2832 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002833 mContext.packageName = admin1.getPackageName();
2834 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2836 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2838 false /* because of non-split user */);
2839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2840 false /* because of non-split user */);
2841 }
2842
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002843 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002844 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002845 setup_nonSplitUser_firstBoot_primaryUser();
2846 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2847 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2848 DevicePolicyManager.CODE_OK);
2849 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2850 DevicePolicyManager.CODE_OK);
2851 assertCheckProvisioningPreCondition(
2852 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2853 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2855 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2856 }
2857
Esteban Talavera01576862016-12-15 11:16:44 +00002858 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002859 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002860 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002861 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2862 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002863 .thenReturn(true);
2864 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2865
2866 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002867 }
Victor Chang3e794af2016-03-04 13:48:17 +00002868
Nicolas Prevot45d29072017-01-18 16:11:19 +00002869 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2870 setDeviceOwner();
2871 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2872 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2873 }
2874
2875 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2876 setup_nonSplitUser_withDo_primaryUser();
2877 final int MANAGED_PROFILE_USER_ID = 18;
2878 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2879 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002880 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002881 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002882 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002883 true)).thenReturn(true);
2884 }
2885
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002886 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2887 throws Exception {
2888 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002889 mContext.packageName = admin1.getPackageName();
2890 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002891 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2892 false/* because of completed device setup */);
2893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2895 false/* because of non-split user */);
2896 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2897 false/* because of non-split user */);
2898 }
2899
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002900 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2901 throws Exception {
2902 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2903 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2904 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2905 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2906 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2907 DevicePolicyManager.CODE_OK);
2908 assertCheckProvisioningPreCondition(
2909 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2910 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2911 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2912 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2913 }
2914
Nicolas Prevot45d29072017-01-18 16:11:19 +00002915 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2916 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002917 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002918 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2919
2920 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2921 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002922 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002923
2924 // COMP mode is allowed.
2925 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2926 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002927 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002928
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002930 assertCheckProvisioningPreCondition(
2931 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002932 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002933 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002934 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2935 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2936 }
Esteban Talavera01576862016-12-15 11:16:44 +00002937
Nicolas Prevot45d29072017-01-18 16:11:19 +00002938 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2939 setup_nonSplitUser_withDo_primaryUser();
2940 mContext.packageName = admin1.getPackageName();
2941 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2942 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2943 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002944 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002945 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2946 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2947 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002948 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002949 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2950 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2951 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2952 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2953 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002954 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002955 assertCheckProvisioningPreCondition(
2956 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002958 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002959 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2960 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2961 }
Esteban Talavera01576862016-12-15 11:16:44 +00002962
Nicolas Prevot45d29072017-01-18 16:11:19 +00002963 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2964 throws Exception {
2965 setup_nonSplitUser_withDo_primaryUser();
2966 mContext.packageName = admin1.getPackageName();
2967 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002968 // The DO should not be allowed to initiate provisioning if the restriction is set by
2969 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002970 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002971 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2972 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2973 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002974 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002975 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2976 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2977 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2978 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2979 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2981
2982 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002983 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002984 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002985 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002986 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2987 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2988 }
2989
2990 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2991 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2992 mContext.packageName = admin1.getPackageName();
2993 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2994
2995 // We can delete the managed profile to create a new one, so provisioning is allowed.
2996 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2997 DevicePolicyManager.CODE_OK);
2998 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2999 assertCheckProvisioningPreCondition(
3000 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3001 DpmMockContext.ANOTHER_PACKAGE_NAME,
3002 DevicePolicyManager.CODE_OK);
3003 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3004 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3005 }
3006
3007 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3008 throws Exception {
3009 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3010 mContext.packageName = admin1.getPackageName();
3011 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003013 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3014 eq(UserHandle.SYSTEM)))
3015 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003016 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003017 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3018 eq(UserHandle.SYSTEM)))
3019 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003020
3021 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003022 assertCheckProvisioningPreCondition(
3023 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3024 DpmMockContext.ANOTHER_PACKAGE_NAME,
3025 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3027 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003028
3029 // But the device owner can still do it because it has set the restriction itself.
3030 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3031 DevicePolicyManager.CODE_OK);
3032 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003033 }
3034
3035 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003037 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3039 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003040 .thenReturn(false);
3041 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3042
3043 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003044 }
Victor Chang3e794af2016-03-04 13:48:17 +00003045
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003046 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3047 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003048 mContext.packageName = admin1.getPackageName();
3049 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003050 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3052 false /* because canAddMoreManagedProfiles returns false */);
3053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3054 true);
3055 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3056 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003057 }
3058
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3060 throws Exception {
3061 setup_splitUser_firstBoot_systemUser();
3062 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3063 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3064 DevicePolicyManager.CODE_OK);
3065 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003066 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003067 assertCheckProvisioningPreCondition(
3068 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3069 DevicePolicyManager.CODE_OK);
3070 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3071 DevicePolicyManager.CODE_SYSTEM_USER);
3072 }
3073
Esteban Talavera01576862016-12-15 11:16:44 +00003074 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003075 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003076 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003077 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3078 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003079 .thenReturn(false);
3080 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3081
3082 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003083 }
Victor Chang3e794af2016-03-04 13:48:17 +00003084
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003085 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3086 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003087 mContext.packageName = admin1.getPackageName();
3088 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3090 true/* it's undefined behavior. Can be changed into false in the future */);
3091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3092 false /* because canAddMoreManagedProfiles returns false */);
3093 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3094 true/* it's undefined behavior. Can be changed into false in the future */);
3095 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3096 false/* because calling uid is system user */);
3097 }
3098
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003099 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3100 throws Exception {
3101 setup_splitUser_afterDeviceSetup_systemUser();
3102 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3103 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3104 DevicePolicyManager.CODE_OK);
3105 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003106 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003107 assertCheckProvisioningPreCondition(
3108 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3109 DevicePolicyManager.CODE_OK);
3110 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3111 DevicePolicyManager.CODE_SYSTEM_USER);
3112 }
3113
Esteban Talavera01576862016-12-15 11:16:44 +00003114 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003115 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003116 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003117 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3118 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003119 true)).thenReturn(true);
3120 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3121
3122 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003123 }
Victor Chang3e794af2016-03-04 13:48:17 +00003124
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003125 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3126 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003127 mContext.packageName = admin1.getPackageName();
3128 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3130 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3131 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3132 true);
3133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003134 }
3135
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003136 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003137 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003138 setup_splitUser_firstBoot_primaryUser();
3139 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3140 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3141 DevicePolicyManager.CODE_OK);
3142 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3143 DevicePolicyManager.CODE_OK);
3144 assertCheckProvisioningPreCondition(
3145 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3146 DevicePolicyManager.CODE_OK);
3147 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3148 DevicePolicyManager.CODE_OK);
3149 }
3150
Esteban Talavera01576862016-12-15 11:16:44 +00003151 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003152 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003153 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003154 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3155 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003156 true)).thenReturn(true);
3157 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3158
3159 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003160 }
Victor Chang3e794af2016-03-04 13:48:17 +00003161
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003162 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3163 throws Exception {
3164 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003165 mContext.packageName = admin1.getPackageName();
3166 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003167 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3168 true/* it's undefined behavior. Can be changed into false in the future */);
3169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3170 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3171 true/* it's undefined behavior. Can be changed into false in the future */);
3172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3173 false/* because user setup completed */);
3174 }
3175
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003176 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003177 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003178 setup_splitUser_afterDeviceSetup_primaryUser();
3179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3180 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3181 DevicePolicyManager.CODE_OK);
3182 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3183 DevicePolicyManager.CODE_OK);
3184 assertCheckProvisioningPreCondition(
3185 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3186 DevicePolicyManager.CODE_OK);
3187 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3188 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3189 }
3190
Esteban Talavera01576862016-12-15 11:16:44 +00003191 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003192 setDeviceOwner();
3193
Pavel Grafov75c0a892017-05-18 17:28:27 +01003194 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003195 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003196 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3197 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003198 .thenReturn(false);
3199 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3200
3201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003202 }
Victor Chang3e794af2016-03-04 13:48:17 +00003203
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003204 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3205 throws Exception {
3206 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003207 mContext.packageName = admin1.getPackageName();
3208 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003209 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3210 false /* can't provision managed profile on system user */);
3211 }
3212
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003213 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003214 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003215 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3216 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3217 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3218 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3219 }
3220
3221 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003222 setDeviceOwner();
3223
Pavel Grafov75c0a892017-05-18 17:28:27 +01003224 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003225 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003226 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3227 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003228 true)).thenReturn(true);
3229 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3230
3231 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003232 }
Victor Chang3e794af2016-03-04 13:48:17 +00003233
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003234 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3235 throws Exception {
3236 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003237 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3238 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003239 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3240 }
3241
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003242 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003243 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3245 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003246
3247 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003248 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3249 DevicePolicyManager.CODE_OK);
3250 }
3251
3252 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003253 setDeviceOwner();
3254
Pavel Grafov75c0a892017-05-18 17:28:27 +01003255 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003256 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003257 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3258 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003259 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3260 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003261 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003262 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003263 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003264 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003265 true)).thenReturn(true);
3266 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3267
3268 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003269 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003270
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003271 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3272 throws Exception {
3273 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003274 mContext.packageName = admin1.getPackageName();
3275 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003276 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3277 }
3278
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003279 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3280 throws Exception {
3281 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3282 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3283 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3284 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3285 }
3286
3287 public void testCheckProvisioningPreCondition_permission() {
3288 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003289 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3290 () -> dpm.checkProvisioningPreCondition(
3291 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003292 }
3293
Victor Chang3577ed22016-08-25 18:49:26 +01003294 public void testForceUpdateUserSetupComplete_permission() {
3295 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003296 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3297 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003298 }
3299
3300 public void testForceUpdateUserSetupComplete_systemUser() {
3301 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3302 // GIVEN calling from user 20
3303 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003304 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3305 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003306 }
3307
3308 public void testForceUpdateUserSetupComplete_userbuild() {
3309 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3310 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3311
3312 final int userId = UserHandle.USER_SYSTEM;
3313 // GIVEN userComplete is false in SettingsProvider
3314 setUserSetupCompleteForUser(false, userId);
3315
3316 // GIVEN userComplete is true in DPM
3317 DevicePolicyManagerService.DevicePolicyData userData =
3318 new DevicePolicyManagerService.DevicePolicyData(userId);
3319 userData.mUserSetupComplete = true;
3320 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3321
3322 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003323 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003324
3325 assertTrue(dpms.hasUserSetupCompleted());
3326
3327 dpm.forceUpdateUserSetupComplete();
3328
3329 // THEN the state in dpms is not changed
3330 assertTrue(dpms.hasUserSetupCompleted());
3331 }
3332
3333 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3334 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3335 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3336
3337 final int userId = UserHandle.USER_SYSTEM;
3338 // GIVEN userComplete is false in SettingsProvider
3339 setUserSetupCompleteForUser(false, userId);
3340
3341 // GIVEN userComplete is true in DPM
3342 DevicePolicyManagerService.DevicePolicyData userData =
3343 new DevicePolicyManagerService.DevicePolicyData(userId);
3344 userData.mUserSetupComplete = true;
3345 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3346
3347 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003348 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003349
3350 assertTrue(dpms.hasUserSetupCompleted());
3351
3352 dpm.forceUpdateUserSetupComplete();
3353
3354 // THEN the state in dpms is not changed
3355 assertFalse(dpms.hasUserSetupCompleted());
3356 }
3357
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003358 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003359 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003360 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003361
3362 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3363 runAsCaller(mAdmin1Context, dpms, dpm -> {
3364 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3365 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003366 }
3367
3368 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3369 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3370 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003371
3372 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3373 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003374 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003375 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3376 .thenReturn(true);
3377
3378 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003379 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003380
3381 // Enabling logging should not change the timestamp.
3382 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003383 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003384 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003385 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003386 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003387 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003388
3389 // Retrieving the logs should update the timestamp.
3390 final long beforeRetrieval = System.currentTimeMillis();
3391 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003392 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003393 final long afterRetrieval = System.currentTimeMillis();
3394 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3395 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3396
3397 // Retrieving the pre-boot logs should update the timestamp.
3398 Thread.sleep(2);
3399 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003400 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003401 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3402
3403 // Checking the timestamp again should not change it.
3404 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003405 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003406
3407 // Retrieving the logs again should update the timestamp.
3408 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003409 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003410 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3411
3412 // Disabling logging should not change the timestamp.
3413 Thread.sleep(2);
3414 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003415 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003416
3417 // Restarting the DPMS should not lose the timestamp.
3418 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003419 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003420
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003421 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3422 mContext.binder.callingUid = 1234567;
3423 mContext.callerPermissions.add(permission.MANAGE_USERS);
3424 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3425 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3426
3427 // System can retrieve the timestamp.
3428 mContext.binder.clearCallingIdentity();
3429 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3430
3431 // Removing the device owner should clear the timestamp.
3432 clearDeviceOwner();
3433 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003434 }
3435
yuemingw0de748d2017-11-15 19:22:27 +00003436 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3437 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3438 setupDeviceOwner();
3439 assertExpectException(SecurityException.class, null, () ->
3440 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3441 }
3442
yuemingwc0281f12018-03-28 15:58:49 +01003443 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003444 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3445 setupDeviceOwner();
3446 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003447 verify(getServices().settings).settingsSystemPutStringForUser(
3448 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3449 }
3450
3451 public void testSetSystemSettingWithPO() throws Exception {
3452 setupProfileOwner();
3453 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3454 verify(getServices().settings).settingsSystemPutStringForUser(
3455 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003456 }
3457
yuemingwe43cdf72017-10-12 16:52:11 +01003458 public void testSetTime() throws Exception {
3459 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3460 setupDeviceOwner();
3461 dpm.setTime(admin1, 0);
3462 verify(getServices().alarmManager).setTime(0);
3463 }
3464
3465 public void testSetTimeFailWithPO() throws Exception {
3466 setupProfileOwner();
3467 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3468 }
3469
3470 public void testSetTimeWithAutoTimeOn() throws Exception {
3471 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3472 setupDeviceOwner();
3473 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3474 .thenReturn(1);
3475 assertFalse(dpm.setTime(admin1, 0));
3476 }
3477
3478 public void testSetTimeZone() throws Exception {
3479 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3480 setupDeviceOwner();
3481 dpm.setTimeZone(admin1, "Asia/Shanghai");
3482 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3483 }
3484
3485 public void testSetTimeZoneFailWithPO() throws Exception {
3486 setupProfileOwner();
3487 assertExpectException(SecurityException.class, null,
3488 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3489 }
3490
3491 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3492 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3493 setupDeviceOwner();
3494 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3495 .thenReturn(1);
3496 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3497 }
3498
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003499 public void testGetLastBugReportRequestTime() throws Exception {
3500 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3501 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003502
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003503 mContext.packageName = admin1.getPackageName();
3504 mContext.applicationInfo = new ApplicationInfo();
3505 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3506 .thenReturn(Color.WHITE);
3507 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3508 anyObject())).thenReturn(Color.WHITE);
3509
Esteban Talaverad36dd152016-12-15 08:51:45 +00003510 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3511 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003512 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003513
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003514 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003515 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003516
3517 // Requesting a bug report should update the timestamp.
3518 final long beforeRequest = System.currentTimeMillis();
3519 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003520 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003521 final long afterRequest = System.currentTimeMillis();
3522 assertTrue(bugReportRequestTime >= beforeRequest);
3523 assertTrue(bugReportRequestTime <= afterRequest);
3524
3525 // Checking the timestamp again should not change it.
3526 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003527 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003528
3529 // Restarting the DPMS should not lose the timestamp.
3530 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003531 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003532
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003533 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3534 mContext.binder.callingUid = 1234567;
3535 mContext.callerPermissions.add(permission.MANAGE_USERS);
3536 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3537 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3538
3539 // System can retrieve the timestamp.
3540 mContext.binder.clearCallingIdentity();
3541 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3542
3543 // Removing the device owner should clear the timestamp.
3544 clearDeviceOwner();
3545 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003546 }
3547
3548 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3549 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3550 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003551 mContext.packageName = admin1.getPackageName();
3552 mContext.applicationInfo = new ApplicationInfo();
3553 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3554 .thenReturn(Color.WHITE);
3555 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3556 anyObject())).thenReturn(Color.WHITE);
3557
3558 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3559 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003560 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003561 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003562 .thenReturn(true);
3563
3564 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003565 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003566
3567 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3568 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003569 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003570
3571 // Enabling logging should not change the timestamp.
3572 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003573 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003574
3575 // Retrieving the logs should update the timestamp.
3576 final long beforeRetrieval = System.currentTimeMillis();
3577 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003578 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003579 final long afterRetrieval = System.currentTimeMillis();
3580 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3581 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3582
3583 // Checking the timestamp again should not change it.
3584 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003585 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003586
3587 // Retrieving the logs again should update the timestamp.
3588 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003589 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003590 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3591
3592 // Disabling logging should not change the timestamp.
3593 Thread.sleep(2);
3594 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003595 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003596
3597 // Restarting the DPMS should not lose the timestamp.
3598 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003599 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3600
3601 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3602 mContext.binder.callingUid = 1234567;
3603 mContext.callerPermissions.add(permission.MANAGE_USERS);
3604 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3605 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3606
3607 // System can retrieve the timestamp.
3608 mContext.binder.clearCallingIdentity();
3609 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3610
3611 // Removing the device owner should clear the timestamp.
3612 clearDeviceOwner();
3613 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003614 }
3615
Tony Mak2f26b792016-11-28 17:54:51 +00003616 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3617 // Setup device owner.
3618 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3619 setupDeviceOwner();
3620
3621 // Only device owner is setup, the result list should be empty.
3622 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3623 MoreAsserts.assertEmpty(targetUsers);
3624
3625 // Setup a managed profile managed by the same admin.
3626 final int MANAGED_PROFILE_USER_ID = 15;
3627 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3628 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3629
3630 // Add a secondary user, it should never talk with.
3631 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003632 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003633
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003634 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3635 // other.
3636 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3637 MoreAsserts.assertEmpty(targetUsers);
3638
3639 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3640 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3641 MoreAsserts.assertEmpty(targetUsers);
3642
3643 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003644 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003645 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3646 dpm.setAffiliationIds(admin1, userAffiliationIds);
3647
3648 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3649 dpm.setAffiliationIds(admin1, userAffiliationIds);
3650
Tony Mak2f26b792016-11-28 17:54:51 +00003651 // Calling from device owner admin, the result list should just contain the managed
3652 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003653 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003654 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3655 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3656
3657 // Calling from managed profile admin, the result list should just contain the system
3658 // user id.
3659 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3660 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3661 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003662
3663 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003664 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003665
3666 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3667 // to each other.
3668 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3669 MoreAsserts.assertEmpty(targetUsers);
3670
3671 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3672 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3673 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003674 }
3675
3676 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3677 // Setup a device owner.
3678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3679 setupDeviceOwner();
3680
3681 // Set up a managed profile managed by different package.
3682 final int MANAGED_PROFILE_USER_ID = 15;
3683 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3684 final ComponentName adminDifferentPackage =
3685 new ComponentName("another.package", "whatever.class");
3686 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3687
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003688 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003689 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003690 dpm.setAffiliationIds(admin1, userAffiliationIds);
3691
3692 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3693 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3694
Tony Mak2f26b792016-11-28 17:54:51 +00003695 // Calling from device owner admin, we should get zero bind device admin target users as
3696 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003697 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003698 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3699 MoreAsserts.assertEmpty(targetUsers);
3700
3701 // Calling from managed profile admin, we should still get zero target users for the same
3702 // reason.
3703 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3704 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3705 MoreAsserts.assertEmpty(targetUsers);
3706 }
3707
Jason Parks3c13b642017-11-28 15:39:43 -06003708 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003709 verifyLockTaskState(userId, new String[0],
3710 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003711 }
3712
3713 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3714 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003715 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003716 }
3717
3718 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3719 int flags) throws Exception {
3720 mContext.binder.callingUid = uid;
3721 dpm.setLockTaskPackages(who, packages);
3722 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3723 for (String p : packages) {
3724 assertTrue(dpm.isLockTaskPermitted(p));
3725 }
3726 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3727 // Test to see if set lock task features can be set
3728 dpm.setLockTaskFeatures(who, flags);
3729 verifyLockTaskState(userId, packages, flags);
3730 }
3731
3732 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3733 int flags) throws Exception {
3734 mContext.binder.callingUid = uid;
3735 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3736 () -> dpm.setLockTaskPackages(who, packages));
3737 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3738 () -> dpm.getLockTaskPackages(who));
3739 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3740 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3741 () -> dpm.setLockTaskFeatures(who, flags));
3742 }
3743
Charles Hee078db72017-10-19 18:03:20 +01003744 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003745 // Setup a device owner.
3746 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3747 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003748 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003749 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003750
3751 // Set up a managed profile managed by different package (package name shouldn't matter)
3752 final int MANAGED_PROFILE_USER_ID = 15;
3753 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3754 final ComponentName adminDifferentPackage =
3755 new ComponentName("another.package", "whatever.class");
3756 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003757 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3758
3759 // Setup a PO on the secondary user
3760 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3761 setAsProfileOwner(admin3);
3762 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003763
3764 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003765 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003766 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003767 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3768 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003769 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3770
3771 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3772 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003773 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3774 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003775 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003776
3777 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3778 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3779 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003780 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003781 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3782 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003783 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003784
3785 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003786 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003787 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3788 dpm.setAffiliationIds(admin1, userAffiliationIds);
3789
3790 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3791 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3792
3793 // Now the managed profile can set lock task packages.
3794 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3795 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3796 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3797 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003798 // And it can set lock task features.
3799 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003800 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003801
3802 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003803 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003804 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3805 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003806 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3807 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003808 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003809 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003810
Jason Parks3c13b642017-11-28 15:39:43 -06003811 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003812 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3813 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003814
3815 }
3816
3817 public void testLockTaskPolicyForProfileOwner() throws Exception {
3818 // Setup a PO
3819 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3820 setAsProfileOwner(admin1);
3821 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3822
3823 final String[] poPackages = {"poPackage1", "poPackage2"};
3824 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003825 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3826 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003827 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3828 poPackages, poFlags);
3829
3830 // Set up a managed profile managed by different package (package name shouldn't matter)
3831 final int MANAGED_PROFILE_USER_ID = 15;
3832 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3833 final ComponentName adminDifferentPackage =
3834 new ComponentName("another.package", "whatever.class");
3835 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3836 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3837
3838 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3839 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3840 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3841 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003842 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3843 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003844 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003845 }
3846
Benjamin Franzcaffa772018-02-05 16:36:10 +00003847 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3848 // Setup a device owner.
3849 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3850 setupDeviceOwner();
3851 // Lock task policy is updated when loading user data.
3852 verifyLockTaskState(UserHandle.USER_SYSTEM);
3853
3854 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3855 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3856 assertExpectException(IllegalArgumentException.class,
3857 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3858 () -> dpm.setLockTaskFeatures(admin1, flags));
3859 }
3860
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003861 public void testIsDeviceManaged() throws Exception {
3862 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3863 setupDeviceOwner();
3864
3865 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3866 // find out that the device has a device owner.
3867 assertTrue(dpm.isDeviceManaged());
3868 mContext.binder.callingUid = 1234567;
3869 mContext.callerPermissions.add(permission.MANAGE_USERS);
3870 assertTrue(dpm.isDeviceManaged());
3871 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3872 mContext.binder.clearCallingIdentity();
3873 assertTrue(dpm.isDeviceManaged());
3874
3875 clearDeviceOwner();
3876
3877 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3878 // not have a device owner.
3879 mContext.binder.callingUid = 1234567;
3880 mContext.callerPermissions.add(permission.MANAGE_USERS);
3881 assertFalse(dpm.isDeviceManaged());
3882 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3883 mContext.binder.clearCallingIdentity();
3884 assertFalse(dpm.isDeviceManaged());
3885 }
3886
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003887 public void testDeviceOwnerOrganizationName() throws Exception {
3888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3889 setupDeviceOwner();
3890
3891 dpm.setOrganizationName(admin1, "organization");
3892
3893 // Device owner can retrieve organization managing the device.
3894 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3895
3896 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3897 mContext.binder.callingUid = 1234567;
3898 mContext.callerPermissions.add(permission.MANAGE_USERS);
3899 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3900 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3901
3902 // System can retrieve organization managing the device.
3903 mContext.binder.clearCallingIdentity();
3904 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3905
3906 // Removing the device owner clears the organization managing the device.
3907 clearDeviceOwner();
3908 assertNull(dpm.getDeviceOwnerOrganizationName());
3909 }
3910
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003911 public void testWipeDataManagedProfile() throws Exception {
3912 final int MANAGED_PROFILE_USER_ID = 15;
3913 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3914 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3915 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3916
3917 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003918 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003919 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003920 // Get mock reason string since we throw an IAE with empty string input.
3921 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3922 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003923
3924 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003925 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003926 MANAGED_PROFILE_USER_ID);
3927 }
3928
3929 public void testWipeDataManagedProfileDisallowed() throws Exception {
3930 final int MANAGED_PROFILE_USER_ID = 15;
3931 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3932 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3933
3934 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003935 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003936 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3937
Pavel Grafov75c0a892017-05-18 17:28:27 +01003938 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003939 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3940 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3941 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003942 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3943 thenReturn("Just a test string.");
3944
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003945 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003946 // The PO is not allowed to remove the profile if the user restriction was set on the
3947 // profile by the system
3948 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3949 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003950 }
3951
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003952 public void testWipeDataDeviceOwner() throws Exception {
3953 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003954 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003955 UserManager.DISALLOW_FACTORY_RESET,
3956 UserHandle.SYSTEM))
3957 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003958 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3959 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003960
3961 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003962 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003963 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3964 /*wipeEuicc=*/ eq(false));
3965 }
3966
3967 public void testWipeEuiccDataEnabled() throws Exception {
3968 setDeviceOwner();
3969 when(getServices().userManager.getUserRestrictionSource(
3970 UserManager.DISALLOW_FACTORY_RESET,
3971 UserHandle.SYSTEM))
3972 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003973 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3974 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003975
3976 dpm.wipeData(WIPE_EUICC);
3977 verify(getServices().recoverySystem).rebootWipeUserData(
3978 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3979 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003980 }
3981
3982 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3983 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003984 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003985 UserManager.DISALLOW_FACTORY_RESET,
3986 UserHandle.SYSTEM))
3987 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003988 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3989 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003990 // The DO is not allowed to wipe the device if the user restriction was set
3991 // by the system
3992 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3993 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003994 }
3995
3996 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3997 final int MANAGED_PROFILE_USER_ID = 15;
3998 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3999 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4000
4001 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004002 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004003 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4004
Pavel Grafov75c0a892017-05-18 17:28:27 +01004005 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004006 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4007 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4008 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4009
4010 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4011 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4012
4013 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4014 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4015 // Failed password attempts on the parent user are taken into account, as there isn't a
4016 // separate work challenge.
4017 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4018 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4019 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4020
4021 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4022 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004023 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004024 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004025 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004026 }
4027
4028 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4029 throws Exception {
4030 final int MANAGED_PROFILE_USER_ID = 15;
4031 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4032 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4033
4034 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004035 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004036 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4037
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004039 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4040 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4041 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4042
4043 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4044 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4045
4046 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4047 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4048 // Failed password attempts on the parent user are taken into account, as there isn't a
4049 // separate work challenge.
4050 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4051 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4052 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4053
4054 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4055 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004056 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004057 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004058 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004059 }
4060
4061 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4062 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004063 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004064 UserManager.DISALLOW_FACTORY_RESET,
4065 UserHandle.SYSTEM))
4066 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4067
4068 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4069
4070 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4071 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4072 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4073 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4074 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4075
4076 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4077 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004078 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004079 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4080 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004081 }
4082
4083 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4084 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004085 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004086 UserManager.DISALLOW_FACTORY_RESET,
4087 UserHandle.SYSTEM))
4088 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4089
4090 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4091
4092 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4093 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4094 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4095 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4096 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4097
4098 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004099 verifyZeroInteractions(getServices().recoverySystem);
4100 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004101 .removeUserEvenWhenDisallowed(anyInt());
4102 }
4103
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004104 public void testGetPermissionGrantState() throws Exception {
4105 final String permission = "some.permission";
4106 final String app1 = "com.example.app1";
4107 final String app2 = "com.example.app2";
4108
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004110 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004111 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004112 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004114 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4115 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004117 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004118 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004119 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004121 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4122
4123 // System can retrieve permission grant state.
4124 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004125 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004126 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4127 dpm.getPermissionGrantState(null, app1, permission));
4128 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4129 dpm.getPermissionGrantState(null, app2, permission));
4130
4131 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004132 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4133 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004134 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4135 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004136
4137 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004138 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4139 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004140 setAsProfileOwner(admin1);
4141 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4142 dpm.getPermissionGrantState(admin1, app1, permission));
4143 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4144 dpm.getPermissionGrantState(admin1, app2, permission));
4145 }
4146
Rubin Xuaab7a412016-12-30 21:13:29 +00004147 public void testResetPasswordWithToken() throws Exception {
4148 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4149 setupDeviceOwner();
4150 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004151 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4152 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4153
Rubin Xuaab7a412016-12-30 21:13:29 +00004154 // test adding a token
4155 final byte[] token = new byte[32];
4156 final long handle = 123456;
4157 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004158 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004159 .thenReturn(handle);
4160 assertTrue(dpm.setResetPasswordToken(admin1, token));
4161
4162 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004164 .thenReturn(true);
4165 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4166
4167 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004168 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004169 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4170 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004171 eq(UserHandle.USER_SYSTEM)))
4172 .thenReturn(true);
4173 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4174
4175 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004176 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004177 .thenReturn(true);
4178 assertTrue(dpm.clearResetPasswordToken(admin1));
4179 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004180
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004181 public void testIsActivePasswordSufficient() throws Exception {
4182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4183 mContext.packageName = admin1.getPackageName();
4184 setupDeviceOwner();
4185
4186 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4187 dpm.setPasswordMinimumLength(admin1, 8);
4188 dpm.setPasswordMinimumLetters(admin1, 6);
4189 dpm.setPasswordMinimumLowerCase(admin1, 3);
4190 dpm.setPasswordMinimumUpperCase(admin1, 1);
4191 dpm.setPasswordMinimumNonLetter(admin1, 1);
4192 dpm.setPasswordMinimumNumeric(admin1, 1);
4193 dpm.setPasswordMinimumSymbols(admin1, 0);
4194
Rubin Xucc391c22018-01-02 20:37:35 +00004195 reset(mContext.spiedContext);
4196
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004197 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4198 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4199 8, 2,
4200 6, 1,
4201 0, 1);
4202
4203 setActivePasswordState(passwordMetricsNoSymbols);
4204 assertTrue(dpm.isActivePasswordSufficient());
4205
4206 initializeDpms();
4207 reset(mContext.spiedContext);
4208 assertTrue(dpm.isActivePasswordSufficient());
4209
4210 // This call simulates the user entering the password for the first time after a reboot.
4211 // This causes password metrics to be reloaded into memory. Until this happens,
4212 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4213 // even if the DPC changes password requirements so that the password no longer meets the
4214 // requirements. This is a known limitation of the current implementation of
4215 // isActivePasswordSufficient() - see b/34218769.
4216 setActivePasswordState(passwordMetricsNoSymbols);
4217 assertTrue(dpm.isActivePasswordSufficient());
4218
4219 dpm.setPasswordMinimumSymbols(admin1, 1);
4220 // This assertion would fail if we had not called setActivePasswordState() again after
4221 // initializeDpms() - see previous comment.
4222 assertFalse(dpm.isActivePasswordSufficient());
4223
4224 initializeDpms();
4225 reset(mContext.spiedContext);
4226 assertFalse(dpm.isActivePasswordSufficient());
4227
4228 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4229 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4230 7, 2,
4231 5, 1,
4232 1, 2);
4233
4234 setActivePasswordState(passwordMetricsWithSymbols);
4235 assertTrue(dpm.isActivePasswordSufficient());
4236 }
4237
Pavel Grafov75c0a892017-05-18 17:28:27 +01004238 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4239 throws Exception {
4240 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004241 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004242
Pavel Grafov75c0a892017-05-18 17:28:27 +01004243 dpm.setActivePasswordState(passwordMetrics, userHandle);
4244 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004245
Rubin Xucc391c22018-01-02 20:37:35 +00004246 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4247 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004248 // This broadcast should be sent 4 times:
4249 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4250 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4251 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4252 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4253 // the password change is relevant to and another with the credential owner of said
4254 // userId.
4255 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004256 MockUtils.checkIntentAction(
4257 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4258 MockUtils.checkUserHandle(userHandle));
4259
Pavel Grafov75c0a892017-05-18 17:28:27 +01004260 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4261 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004262 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004263
4264 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4265 MockUtils.checkIntent(intent),
4266 MockUtils.checkUserHandle(userHandle));
4267
4268 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4269 // let it finish with system uid, otherwise it will throw and crash.
4270 flushTasks();
4271
4272 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004273 }
4274
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004275 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4276 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4277 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4278 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4279 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4280 DpmMockContext.SYSTEM_UID);
4281 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4282 DpmMockContext.SYSTEM_UID);
4283
4284 // Set up a device owner.
4285 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004286 setupDeviceOwner();
4287
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004288 // First and second user set IMEs manually.
4289 mContext.binder.callingUid = firstUserSystemUid;
4290 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4291 mContext.binder.callingUid = secondUserSystemUid;
4292 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004293
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004294 // Device owner changes IME for first user.
4295 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004296 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004297 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004298 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004299 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004300 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004301 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004302 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4303 mContext.binder.callingUid = firstUserSystemUid;
4304 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4305 mContext.binder.callingUid = secondUserSystemUid;
4306 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004307
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004308 // Second user changes IME manually.
4309 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4310 mContext.binder.callingUid = firstUserSystemUid;
4311 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4312 mContext.binder.callingUid = secondUserSystemUid;
4313 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004314
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004315 // First user changes IME manually.
4316 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4317 mContext.binder.callingUid = firstUserSystemUid;
4318 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4319 mContext.binder.callingUid = secondUserSystemUid;
4320 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004321
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004322 // Device owner changes IME for first user again.
4323 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004324 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004325 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004326 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004327 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004328 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004329 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4330 mContext.binder.callingUid = firstUserSystemUid;
4331 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4332 mContext.binder.callingUid = secondUserSystemUid;
4333 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004334
4335 // Restarting the DPMS should not lose information.
4336 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004337 mContext.binder.callingUid = firstUserSystemUid;
4338 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4339 mContext.binder.callingUid = secondUserSystemUid;
4340 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004341
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004342 // Device owner can find out whether it set the current IME itself.
4343 mContext.binder.callingUid = deviceOwnerUid;
4344 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004345
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004346 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004347 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004348 mContext.binder.callingUid = firstUserSystemUid;
4349 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4350 mContext.binder.callingUid = secondUserSystemUid;
4351 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004352 }
4353
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004354 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4355 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4356 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4357 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4358 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4359 DpmMockContext.SYSTEM_UID);
4360 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4361 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004362
4363 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004364 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004365 setupProfileOwner();
4366
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004367 // First and second user set IMEs manually.
4368 mContext.binder.callingUid = firstUserSystemUid;
4369 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4370 mContext.binder.callingUid = secondUserSystemUid;
4371 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004372
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004373 // Profile owner changes IME for second user.
4374 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004375 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004376 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004378 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004379 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004380 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4382 mContext.binder.callingUid = firstUserSystemUid;
4383 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4384 mContext.binder.callingUid = secondUserSystemUid;
4385 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004386
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004387 // First user changes IME manually.
4388 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4389 mContext.binder.callingUid = firstUserSystemUid;
4390 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4391 mContext.binder.callingUid = secondUserSystemUid;
4392 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004393
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004394 // Second user changes IME manually.
4395 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4396 mContext.binder.callingUid = firstUserSystemUid;
4397 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4398 mContext.binder.callingUid = secondUserSystemUid;
4399 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004400
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 // Profile owner changes IME for second user again.
4402 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004403 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004404 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004405 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004406 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004407 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004408 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4409 mContext.binder.callingUid = firstUserSystemUid;
4410 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4411 mContext.binder.callingUid = secondUserSystemUid;
4412 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004413
4414 // Restarting the DPMS should not lose information.
4415 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004416 mContext.binder.callingUid = firstUserSystemUid;
4417 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4418 mContext.binder.callingUid = secondUserSystemUid;
4419 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004421 // Profile owner can find out whether it set the current IME itself.
4422 mContext.binder.callingUid = profileOwnerUid;
4423 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004424
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004425 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004426 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004427 mContext.binder.callingUid = firstUserSystemUid;
4428 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4429 mContext.binder.callingUid = secondUserSystemUid;
4430 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004431 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004432
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004433 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4434 throws Exception {
4435 // Set up a device owner.
4436 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4437 setupDeviceOwner();
4438 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4439 }
4440
4441 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4442 throws Exception {
4443 // Set up a profile owner.
4444 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4445 setupProfileOwner();
4446 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4447 }
4448
4449 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4450 int adminUid) throws Exception {
4451 mContext.binder.callingUid = adminUid;
4452 final int userId = UserHandle.getUserId(adminUid);
4453
4454 final String packageName = "some.package";
4455 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4456 admin1, Collections.singletonList(packageName)));
4457 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4458
4459 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4460 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4461
4462 // Attempt to set to empty list (which means no listener is whitelisted)
4463 mContext.binder.callingUid = adminUid;
4464 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004465 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004466 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4467
4468 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4469 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4470 }
4471
4472 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4473 // Set up a managed profile
4474 final int MANAGED_PROFILE_USER_ID = 15;
4475 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4476 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4477 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4478
4479 final String permittedListener = "some.package";
4480 setupPackageInPackageManager(
4481 permittedListener,
4482 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4483 /*appId=*/ 12345, /*flags=*/ 0);
4484
4485 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4486 admin1, Collections.singletonList(permittedListener)));
4487
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004488 // isNotificationListenerServicePermitted should throw if not called from System.
4489 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4490 () -> dpms.isNotificationListenerServicePermitted(
4491 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004492
4493 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4494 assertTrue(dpms.isNotificationListenerServicePermitted(
4495 permittedListener, MANAGED_PROFILE_USER_ID));
4496 }
4497
4498 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4499 throws Exception {
4500 // Set up a managed profile
4501 final int MANAGED_PROFILE_USER_ID = 15;
4502 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4503 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4504 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4505
4506 final String permittedListener = "permitted.package";
4507 int appId = 12345;
4508 setupPackageInPackageManager(
4509 permittedListener,
4510 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4511 appId, /*flags=*/ 0);
4512
4513 final String notPermittedListener = "not.permitted.package";
4514 setupPackageInPackageManager(
4515 notPermittedListener,
4516 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4517 ++appId, /*flags=*/ 0);
4518
4519 final String systemListener = "system.package";
4520 setupPackageInPackageManager(
4521 systemListener,
4522 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4523 ++appId, ApplicationInfo.FLAG_SYSTEM);
4524
4525 // By default all packages are allowed
4526 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4527
4528 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4529 assertTrue(dpms.isNotificationListenerServicePermitted(
4530 permittedListener, MANAGED_PROFILE_USER_ID));
4531 assertTrue(dpms.isNotificationListenerServicePermitted(
4532 notPermittedListener, MANAGED_PROFILE_USER_ID));
4533 assertTrue(dpms.isNotificationListenerServicePermitted(
4534 systemListener, MANAGED_PROFILE_USER_ID));
4535
4536 // Setting only one package in the whitelist
4537 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4538 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4539 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004540 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004541 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4542 assertEquals(1, permittedListeners.size());
4543 assertEquals(permittedListener, permittedListeners.get(0));
4544
4545 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4546 assertTrue(dpms.isNotificationListenerServicePermitted(
4547 permittedListener, MANAGED_PROFILE_USER_ID));
4548 assertFalse(dpms.isNotificationListenerServicePermitted(
4549 notPermittedListener, MANAGED_PROFILE_USER_ID));
4550 // System packages are always allowed (even if not in the whitelist)
4551 assertTrue(dpms.isNotificationListenerServicePermitted(
4552 systemListener, MANAGED_PROFILE_USER_ID));
4553
4554 // Setting an empty whitelist - only system listeners allowed
4555 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4556 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004557 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004558 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4559
4560 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4561 assertFalse(dpms.isNotificationListenerServicePermitted(
4562 permittedListener, MANAGED_PROFILE_USER_ID));
4563 assertFalse(dpms.isNotificationListenerServicePermitted(
4564 notPermittedListener, MANAGED_PROFILE_USER_ID));
4565 // System packages are always allowed (even if not in the whitelist)
4566 assertTrue(dpms.isNotificationListenerServicePermitted(
4567 systemListener, MANAGED_PROFILE_USER_ID));
4568
4569 // Setting a null whitelist - all listeners allowed
4570 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4571 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4572 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4573
4574 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4575 assertTrue(dpms.isNotificationListenerServicePermitted(
4576 permittedListener, MANAGED_PROFILE_USER_ID));
4577 assertTrue(dpms.isNotificationListenerServicePermitted(
4578 notPermittedListener, MANAGED_PROFILE_USER_ID));
4579 assertTrue(dpms.isNotificationListenerServicePermitted(
4580 systemListener, MANAGED_PROFILE_USER_ID));
4581 }
4582
4583 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4584 throws Exception {
4585 // Set up a managed profile
4586 final int MANAGED_PROFILE_USER_ID = 15;
4587 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4588 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4589 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4590
4591 final String nonSystemPackage = "non.system.package";
4592 int appId = 12345;
4593 setupPackageInPackageManager(
4594 nonSystemPackage,
4595 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4596 appId, /*flags=*/ 0);
4597
4598 final String systemListener = "system.package";
4599 setupPackageInPackageManager(
4600 systemListener,
4601 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4602 ++appId, ApplicationInfo.FLAG_SYSTEM);
4603
4604 // By default all packages are allowed (for all profiles)
4605 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4606
4607 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4608 assertTrue(dpms.isNotificationListenerServicePermitted(
4609 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4610 assertTrue(dpms.isNotificationListenerServicePermitted(
4611 systemListener, MANAGED_PROFILE_USER_ID));
4612 assertTrue(dpms.isNotificationListenerServicePermitted(
4613 nonSystemPackage, UserHandle.USER_SYSTEM));
4614 assertTrue(dpms.isNotificationListenerServicePermitted(
4615 systemListener, UserHandle.USER_SYSTEM));
4616
4617 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4618 // all allowed in primary profile
4619 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4620 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004621 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004622 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4623
4624 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4625 assertFalse(dpms.isNotificationListenerServicePermitted(
4626 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4627 assertTrue(dpms.isNotificationListenerServicePermitted(
4628 systemListener, MANAGED_PROFILE_USER_ID));
4629 assertTrue(dpms.isNotificationListenerServicePermitted(
4630 nonSystemPackage, UserHandle.USER_SYSTEM));
4631 assertTrue(dpms.isNotificationListenerServicePermitted(
4632 systemListener, UserHandle.USER_SYSTEM));
4633 }
4634
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004635 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004636 mServiceContext.packageName = mRealTestContext.getPackageName();
4637 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4638 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004639 setDeviceOwner();
4640
Pavel Grafov75c0a892017-05-18 17:28:27 +01004641 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004642 }
4643
4644 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004645 mServiceContext.packageName = mRealTestContext.getPackageName();
4646 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4647 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004648 setAsProfileOwner(admin1);
4649
Pavel Grafov75c0a892017-05-18 17:28:27 +01004650 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4651 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004652 }
4653
4654 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004655 mServiceContext.packageName = mRealTestContext.getPackageName();
4656 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4657 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004658 setAsProfileOwner(admin1);
4659
Pavel Grafov75c0a892017-05-18 17:28:27 +01004660 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4661 caller.packageName = "com.example.delegate";
4662 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4663 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004664
Pavel Grafov75c0a892017-05-18 17:28:27 +01004665 // Make caller a delegated cert installer.
4666 runAsCaller(mAdmin1Context, dpms,
4667 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004668
4669 verifyCanGetOwnerInstalledCaCerts(null, caller);
4670 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004671 }
4672
Rubin Xucc391c22018-01-02 20:37:35 +00004673 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004674 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4675 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004676 Bundle restriction = new Bundle();
4677 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4678
4679 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4680 RestrictionsListener listener = new RestrictionsListener(mContext);
4681 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4682 new Bundle());
4683 verifyDataSharingChangedBroadcast();
4684 }
4685
4686 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004687 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4688 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004689 Bundle restriction = new Bundle();
4690 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4691
4692 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4693 RestrictionsListener listener = new RestrictionsListener(mContext);
4694 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4695 restriction);
4696 verifyDataSharingChangedBroadcast();
4697 }
4698
4699 public void testDisallowSharingIntoProfileUnchanged() {
4700 RestrictionsListener listener = new RestrictionsListener(mContext);
4701 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4702 new Bundle());
4703 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4704 }
4705
4706 private void verifyDataSharingChangedBroadcast() {
4707 Intent expectedIntent = new Intent(
4708 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4709 expectedIntent.setPackage("com.android.managedprovisioning");
4710 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4711 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4712 MockUtils.checkIntent(expectedIntent),
4713 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4714 }
4715
yuemingwe3d9c092018-01-11 12:11:44 +00004716 public void testOverrideApnAPIsFailWithPO() throws Exception {
4717 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004718 ApnSetting apn = (new ApnSetting.Builder())
4719 .setApnName("test")
4720 .setEntryName("test")
4721 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4722 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004723 assertExpectException(SecurityException.class, null, () ->
4724 dpm.addOverrideApn(admin1, apn));
4725 assertExpectException(SecurityException.class, null, () ->
4726 dpm.updateOverrideApn(admin1, 0, apn));
4727 assertExpectException(SecurityException.class, null, () ->
4728 dpm.removeOverrideApn(admin1, 0));
4729 assertExpectException(SecurityException.class, null, () ->
4730 dpm.getOverrideApns(admin1));
4731 assertExpectException(SecurityException.class, null, () ->
4732 dpm.setOverrideApnsEnabled(admin1, false));
4733 assertExpectException(SecurityException.class, null, () ->
4734 dpm.isOverrideApnEnabled(admin1));
4735 }
4736
Robin Lee2c68dad2017-03-17 12:50:24 +00004737 private void verifyCanGetOwnerInstalledCaCerts(
4738 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004739 final String alias = "cert";
4740 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004741
4742 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004743 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004744 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4745 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004746 }
4747 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4748
4749 // caller: device admin or delegated certificate installer
4750 callerContext.applicationInfo = new ApplicationInfo();
4751 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4752
4753 // system_server
4754 final DpmMockContext serviceContext = mContext;
4755 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004756 getServices().addPackageContext(callerUser, admin1Context);
4757 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004758
4759 // Install a CA cert.
4760 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004761 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004762 .thenReturn(alias);
4763 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004764 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004765 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004766 });
4767
Pavel Grafov75c0a892017-05-18 17:28:27 +01004768 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4769 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4770 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004771 flushTasks();
4772
Robin Lee2c68dad2017-03-17 12:50:24 +00004773 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4774
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004775 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004776 runAsCaller(admin1Context, dpms, (dpm) -> {
4777 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004778 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004779 ownerInstalledCaCerts.addAll(installedCaCerts);
4780 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004781
4782 // Restarting the DPMS should not lose information.
4783 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004784 runAsCaller(admin1Context, dpms, (dpm) ->
4785 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004786
4787 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004788 runAsCaller(serviceContext, dpms, (dpm) -> {
4789 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004790
Robin Lee2c68dad2017-03-17 12:50:24 +00004791 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004792 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004793 });
4794
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4796 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4797 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004798 flushTasks();
4799
4800 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4801 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004802 runAsCaller(admin1Context, dpms, (dpm) -> {
4803 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4804 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004805 }
4806
Robin Lee2c68dad2017-03-17 12:50:24 +00004807 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4808 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004809 final String alias = "cert";
4810 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004811
4812 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004813 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004814 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4815 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004816 }
4817 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4818
4819 // caller: device admin or delegated certificate installer
4820 callerContext.applicationInfo = new ApplicationInfo();
4821 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4822
4823 // system_server
4824 final DpmMockContext serviceContext = mContext;
4825 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004826 getServices().addPackageContext(callerUser, admin1Context);
4827 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004828
4829 // Install a CA cert as caller
4830 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004831 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004832 .thenReturn(alias);
4833 assertTrue(dpm.installCaCert(callerName, caCert));
4834 });
4835
4836 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004837 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004838 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004839 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4840 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4841 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004842 flushTasks();
4843
Robin Lee2c68dad2017-03-17 12:50:24 +00004844 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004845 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004846
4847 runAsCaller(serviceContext, dpms, (dpm) -> {
4848 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4849 assertNotNull(ownerInstalledCaCerts);
4850 assertTrue(ownerInstalledCaCerts.isEmpty());
4851 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004852 }
4853
Eran Messeri94d56762017-12-21 20:50:54 +00004854 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4855 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4856 Arrays.sort(gotFlags);
4857 Arrays.sort(expectedFlags);
4858 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4859 }
4860
4861 public void testTranslationOfIdAttestationFlag() {
4862 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4863 int[] correspondingAttUtilsTypes = new int[]{
4864 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4865 AttestationUtils.ID_TYPE_MEID};
4866
4867 // Test translation of zero flags
4868 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4869
4870 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4871 // non-null array
4872 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4873
4874 // Test translation of a single flag
4875 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4876 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4877 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4878
4879 // Test translation of two flags
4880 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4881 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4882 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4883 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4884
4885 // Test translation of all three flags
4886 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4887 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4888 AttestationUtils.ID_TYPE_MEID});
4889 // Test translation of all three flags
4890 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4891 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4892 AttestationUtils.ID_TYPE_MEID});
4893 }
4894
arangelov08d534b2018-01-22 15:20:53 +00004895 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4896 setDeviceOwner();
4897 initializeDpms();
4898 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4899 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4900 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4901 }
4902
4903 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4904 DpmTestUtils.writeInputStreamToFile(
4905 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4906 getDeviceOwnerPoliciesFile());
4907 DpmTestUtils.writeInputStreamToFile(
4908 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4909 getDeviceOwnerFile());
4910 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4911 }
4912
4913 public void testRevertDeviceOwnership_deviceNotMigrated()
4914 throws Exception {
4915 DpmTestUtils.writeInputStreamToFile(
4916 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4917 getDeviceOwnerPoliciesFile());
4918 DpmTestUtils.writeInputStreamToFile(
4919 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4920 getDeviceOwnerFile());
4921 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4922 }
4923
4924 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4925 throws Exception {
4926 DpmTestUtils.writeInputStreamToFile(
4927 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4928 getDeviceOwnerPoliciesFile());
4929 DpmTestUtils.writeInputStreamToFile(
4930 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4931 getDeviceOwnerFile());
4932 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4933 }
4934
4935 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4936 setupProfileOwner();
4937 initializeDpms();
4938 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4939 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4940 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4941 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4942 }
4943
4944 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4945 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4946 UserHandle.USER_SYSTEM);
4947 DpmTestUtils.writeInputStreamToFile(
4948 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4949 getProfileOwnerPoliciesFile());
4950 DpmTestUtils.writeInputStreamToFile(
4951 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4952 getProfileOwnerFile());
4953 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4954 }
4955
4956 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4957 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4958 UserHandle.USER_SYSTEM);
4959 DpmTestUtils.writeInputStreamToFile(
4960 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4961 getProfileOwnerPoliciesFile());
4962 DpmTestUtils.writeInputStreamToFile(
4963 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4964 getProfileOwnerFile());
4965 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4966 }
4967
4968 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
4969 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4970 UserHandle.USER_SYSTEM);
4971 DpmTestUtils.writeInputStreamToFile(
4972 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4973 getProfileOwnerPoliciesFile());
4974 DpmTestUtils.writeInputStreamToFile(
4975 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4976 getProfileOwnerFile());
4977 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4978 }
4979
Eran Messeribb271892018-10-17 18:27:50 +01004980 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
4981 setupProfileOwner();
4982 configureContextForAccess(mContext, false);
4983
4984 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4985 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin2,
4986 UserHandle.of(DpmMockContext.CALLER_UID)));
4987 }
4988
4989 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
4990 setupProfileOwner();
4991 configureContextForAccess(mContext, false);
4992
4993 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4994 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
4995 UserHandle.of(DpmMockContext.CALLER_UID)));
4996 }
4997
4998 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
4999 setupProfileOwner();
5000
5001 // This method will throw if the system context could not call
5002 // setProfileOwnerCanAccessDeviceIds successfully.
5003 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5004 }
5005
5006 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5007 when(context.spiedContext.checkCallingPermission(
5008 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5009 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5010 : PackageManager.PERMISSION_DENIED);
5011 }
5012
5013 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5014 setupProfileOwner();
5015
5016 final long ident = mServiceContext.binder.clearCallingIdentity();
5017 configureContextForAccess(mServiceContext, true);
5018
5019 mServiceContext.binder.callingUid =
5020 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5021 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5022 try {
5023 runAsCaller(mServiceContext, dpms, dpm -> {
5024 dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5025 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE));
5026 });
5027 } finally {
5028 mServiceContext.binder.restoreCallingIdentity(ident);
5029 }
5030 }
5031
5032 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5033 throws Exception {
5034 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5035 setupDeviceOwner();
5036 configureContextForAccess(mContext, false);
5037
5038 // Device owner should be allowed to request Device ID attestation.
5039 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5040 DpmMockContext.CALLER_SYSTEM_USER_UID);
5041
5042 // Another package must not be allowed to request Device ID attestation.
5043 assertExpectException(SecurityException.class, null,
5044 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5045 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5046 // Another component that is not the admin must not be allowed to request Device ID
5047 // attestation.
5048 assertExpectException(SecurityException.class, null,
5049 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5050 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5051 }
5052
5053 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5054 throws Exception {
5055 configureContextForAccess(mContext, false);
5056
5057 // Make sure a security exception is thrown if the device has no profile owner.
5058 assertExpectException(SecurityException.class, null,
5059 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5060 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5061
5062 setupProfileOwner();
5063 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5064
5065 // The profile owner is allowed to request Device ID attestation.
5066 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5067 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5068 DpmMockContext.CALLER_UID);
5069 // But not another package.
5070 assertExpectException(SecurityException.class, null,
5071 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5072 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5073 // Or another component which is not the admin.
5074 assertExpectException(SecurityException.class, null,
5075 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5076 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5077 }
5078
5079 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5080 final long ident = mServiceContext.binder.clearCallingIdentity();
5081
5082 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5083 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5084 try {
5085 runAsCaller(mServiceContext, dpms, action);
5086 } finally {
5087 mServiceContext.binder.restoreCallingIdentity(ident);
5088 }
5089 }
5090
5091 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5092 setupProfileOwner();
5093 markDelegatedCertInstallerAsInstalled();
5094
5095 // Configure a delegated cert installer.
5096 runAsCaller(mServiceContext, dpms,
5097 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5098 Arrays.asList(DELEGATION_CERT_INSTALL)));
5099
5100 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5101
5102 // Make sure that the profile owner can still request Device ID attestation.
5103 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5104 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5105 DpmMockContext.CALLER_UID);
5106
5107 runAsDelegatedCertInstaller(dpm -> {
5108 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5109 DpmMockContext.DELEGATE_PACKAGE_NAME,
5110 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5111 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5112 });
5113 }
5114
5115 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5116 throws Exception {
5117 setupProfileOwner();
5118 markDelegatedCertInstallerAsInstalled();
5119
5120 // Configure a delegated cert installer.
5121 runAsCaller(mServiceContext, dpms,
5122 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5123 Arrays.asList(DELEGATION_CERT_INSTALL)));
5124
5125
5126 assertExpectException(SecurityException.class, null,
5127 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5128 admin1.getPackageName(),
5129 DpmMockContext.CALLER_UID));
5130
5131 runAsDelegatedCertInstaller(dpm -> {
5132 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5133 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5134 DpmMockContext.DELEGATE_PACKAGE_NAME,
5135 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5136 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5137 });
5138 }
5139
Bernard Chaue9586552018-11-29 10:59:31 +00005140 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5141 assertThrows(SecurityException.class,
5142 () -> new DevicePolicyManagerTestable(
5143 mServiceContext,
5144 dpms,
5145 /* parentInstance= */ true)
5146 .getPasswordComplexity());
5147 }
5148
5149 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5150 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5151 .thenReturn(false);
5152 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5153 }
5154
5155 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5156 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5157 .thenReturn(true);
5158 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5159 }
5160
5161
5162 public void testGetPasswordComplexity_currentUserNoPassword() {
5163 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5164 .thenReturn(true);
5165 mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
5166 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5167 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5168
5169 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5170 }
5171
5172 public void testGetPasswordComplexity_currentUserHasPassword() {
5173 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5174 .thenReturn(true);
5175 mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
5176 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5177 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5178 dpms.mUserPasswordMetrics.put(
5179 DpmMockContext.CALLER_USER_HANDLE,
5180 PasswordMetrics.computeForPassword("asdf"));
5181
5182 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5183 }
5184
5185 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5186 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5187 .thenReturn(true);
5188 mServiceContext.permissions.add(permission.GET_AND_REQUEST_SCREEN_LOCK_COMPLEXITY);
5189
5190 UserInfo parentUser = new UserInfo();
5191 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5192 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5193 .thenReturn(parentUser.id);
5194
5195 dpms.mUserPasswordMetrics.put(
5196 DpmMockContext.CALLER_USER_HANDLE,
5197 PasswordMetrics.computeForPassword("asdf"));
5198 dpms.mUserPasswordMetrics.put(
5199 parentUser.id,
5200 PasswordMetrics.computeForPassword("parentUser"));
5201
5202 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5203 }
5204
Eran Messeribb271892018-10-17 18:27:50 +01005205 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5206 final long ident = mServiceContext.binder.clearCallingIdentity();
5207 mServiceContext.binder.callingUid =
5208 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5209 runAsCaller(mServiceContext, dpms, dpm -> {
5210 dpm.setProfileOwnerCanAccessDeviceIdsForUser(who, UserHandle.of(userId));
5211 });
5212 mServiceContext.binder.restoreCallingIdentity(ident);
5213 }
5214
arangelov08d534b2018-01-22 15:20:53 +00005215 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5216 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5217 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5218 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5219
5220 final long ident = mServiceContext.binder.clearCallingIdentity();
5221 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5222 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5223 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5224 // To simulate a reboot, we just reinitialize dpms and call systemReady
5225 initializeDpms();
5226
5227 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5228 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5229 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5230 assertTrue(dpm.isAdminActive(admin1));
5231 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5232 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5233
5234 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5235 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5236 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5237 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5238
5239 mServiceContext.binder.restoreCallingIdentity(ident);
5240 }
5241
5242 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5243 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5244 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5245 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5246
5247 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5248 DpmMockContext.CALLER_SYSTEM_USER_UID);
5249 setUpPackageManagerForAdmin(admin1, uid);
5250 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5251 // To simulate a reboot, we just reinitialize dpms and call systemReady
5252 initializeDpms();
5253
5254 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5255 assertTrue(dpm.isAdminActive(admin1));
5256 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5257 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5258 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5259 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5260 }
5261
5262 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5263 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5264 metadataManager.deleteMetadataFile();
5265
5266 final TransferOwnershipMetadataManager.Metadata metadata =
5267 new TransferOwnershipMetadataManager.Metadata(
5268 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5269 callerUserHandle,
5270 adminType);
5271 metadataManager.saveMetadataFile(metadata);
5272 }
5273
5274 private File getDeviceOwnerFile() {
5275 return dpms.mOwners.getDeviceOwnerFile();
5276 }
5277
5278 private File getProfileOwnerFile() {
5279 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5280 }
5281
5282 private File getProfileOwnerPoliciesFile() {
5283 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5284 DpmMockContext.CALLER_USER_HANDLE);
5285 return getPoliciesFile(parentDir);
5286 }
5287
5288 private File getDeviceOwnerPoliciesFile() {
5289 return getPoliciesFile(getServices().systemUserDataDir);
5290 }
5291
5292 private File getPoliciesFile(File parentDir) {
5293 return new File(parentDir, "device_policies.xml");
5294 }
5295
5296 private InputStream getRawStream(@RawRes int id) {
5297 return mRealTestContext.getResources().openRawResource(id);
5298 }
5299
Victor Chang3e794af2016-03-04 13:48:17 +00005300 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005301 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005302 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5303 dpms.notifyChangeToContentObserver(
5304 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5305 }
5306
5307 private void assertProvisioningAllowed(String action, boolean expected) {
5308 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5309 dpm.isProvisioningAllowed(action));
5310 }
Tony Mak2f26b792016-11-28 17:54:51 +00005311
Nicolas Prevot45d29072017-01-18 16:11:19 +00005312 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5313 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005314 final String previousPackageName = mContext.packageName;
5315 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005316
5317 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5318 mContext.packageName = packageName;
5319 mMockContext.binder.callingUid = uid;
5320 assertProvisioningAllowed(action, expected);
5321
5322 // Set the previous package name / calling uid to go back to the initial state.
5323 mContext.packageName = previousPackageName;
5324 mMockContext.binder.callingUid = previousUid;
5325 }
5326
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005327 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005328 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5329 }
5330
5331 private void assertCheckProvisioningPreCondition(
5332 String action, String packageName, int provisioningCondition) {
5333 assertEquals("checkProvisioningPreCondition("
5334 + action + ", " + packageName + ") returning unexpected result",
5335 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005336 }
5337
Tony Mak2f26b792016-11-28 17:54:51 +00005338 /**
5339 * Setup a managed profile with the specified admin and its uid.
5340 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5341 * @param adminUid uid of the admin package.
5342 * @param copyFromAdmin package information for {@code admin} will be built based on this
5343 * component's information.
5344 */
5345 private void addManagedProfile(
5346 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5347 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005348 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005349 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5350 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5351 dpm.setActiveAdmin(admin, false, userId);
5352 assertTrue(dpm.setProfileOwner(admin, null, userId));
5353 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5354 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005355
5356 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005357 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005358 */
Robin Leeabaa0692017-02-20 20:54:22 +00005359 private static StringParceledListSlice asSlice(String[] s) {
5360 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005361 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005362
5363 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005364 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5365 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005366
Robin Lee2c68dad2017-03-17 12:50:24 +00005367 // We can't let exceptions happen on the background thread. Throw them here if they happen
5368 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005369 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005370 }
Victor Chang3e794af2016-03-04 13:48:17 +00005371}