blob: 039a4b74dbdda6f85907d4f7988bdb0e2b12563b [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
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Pavel Grafov75c0a892017-05-18 17:28:27 +010035import static org.mockito.Matchers.any;
36import static org.mockito.Matchers.anyInt;
37import static org.mockito.Matchers.anyLong;
38import static org.mockito.Matchers.anyObject;
39import static org.mockito.Matchers.anyString;
40import static org.mockito.Matchers.eq;
41import static org.mockito.Matchers.isNull;
42import static org.mockito.Mockito.atLeast;
43import static org.mockito.Mockito.doAnswer;
44import static org.mockito.Mockito.doReturn;
45import static org.mockito.Mockito.never;
46import static org.mockito.Mockito.nullable;
47import static org.mockito.Mockito.reset;
48import static org.mockito.Mockito.timeout;
49import static org.mockito.Mockito.times;
50import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080051import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010052import static org.mockito.Mockito.verifyZeroInteractions;
53import static org.mockito.Mockito.when;
54import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000055import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056
Makoto Onukif76b06a2015-09-22 15:03:44 -070057import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000058import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000060import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import android.app.admin.DeviceAdminReceiver;
62import android.app.admin.DevicePolicyManager;
63import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010064import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070065import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000068import android.content.pm.ApplicationInfo;
69import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010071import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000072import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000073import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010074import android.graphics.Color;
75import android.net.Uri;
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();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100210
211 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700212 }
213
arangelov08d534b2018-01-22 15:20:53 +0000214 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
215 return dpms.mTransferOwnershipMetadataManager;
216 }
217
Robin Lee2c68dad2017-03-17 12:50:24 +0000218 @Override
219 protected void tearDown() throws Exception {
220 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000221 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000222 super.tearDown();
223 }
224
Makoto Onukia52562c2015-10-01 16:12:31 -0700225 private void initializeDpms() {
226 // Need clearCallingIdentity() to pass permission checks.
227 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100228 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700229
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
231 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
232 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700233
Pavel Grafov75c0a892017-05-18 17:28:27 +0100234 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237 }
238
Makoto Onukib643fb02015-09-22 15:03:44 -0700239 private void setUpUserManager() {
240 // Emulate UserManager.set/getApplicationRestriction().
241 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
242
243 // UM.setApplicationRestrictions() will save to appRestrictions.
244 doAnswer(new Answer<Void>() {
245 @Override
246 public Void answer(InvocationOnMock invocation) throws Throwable {
247 String pkg = (String) invocation.getArguments()[0];
248 Bundle bundle = (Bundle) invocation.getArguments()[1];
249 UserHandle user = (UserHandle) invocation.getArguments()[2];
250
251 appRestrictions.put(Pair.create(pkg, user), bundle);
252
253 return null;
254 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100255 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100256 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700257
258 // UM.getApplicationRestrictions() will read from appRestrictions.
259 doAnswer(new Answer<Bundle>() {
260 @Override
261 public Bundle answer(InvocationOnMock invocation) throws Throwable {
262 String pkg = (String) invocation.getArguments()[0];
263 UserHandle user = (UserHandle) invocation.getArguments()[1];
264
265 return appRestrictions.get(Pair.create(pkg, user));
266 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700268 anyString(), any(UserHandle.class));
269
Makoto Onukid932f762015-09-29 16:53:38 -0700270 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700272 }
273
274 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100275 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700276
Pavel Grafov75c0a892017-05-18 17:28:27 +0100277 mServiceContext.binder.callingUid =
278 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
279 runAsCaller(mServiceContext, dpms, dpm -> {
280 // PO needs to be a DA.
281 dpm.setActiveAdmin(admin, /*replace=*/ false);
282 // Fire!
283 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
284 // Check
285 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
286 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700287
Pavel Grafov75c0a892017-05-18 17:28:27 +0100288 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700289 }
290
291 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100292 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700293 .thenReturn(false);
294
295 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100296 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700297
298 // If the device has no DPMS feature, it shouldn't register the local service.
299 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
300 }
301
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800302 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800303 // Device owner in SYSTEM_USER
304 setDeviceOwner();
305 // Profile owner in CALLER_USER_HANDLE
306 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
307 setAsProfileOwner(admin2);
308 // Active admin in CALLER_USER_HANDLE
309 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
310 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
311 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
312 DpmMockContext.CALLER_USER_HANDLE);
313 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
314 DpmMockContext.CALLER_USER_HANDLE));
315
316 initializeDpms();
317
318 // Verify
319 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800320 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800321 eq(UserHandle.USER_SYSTEM));
322 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800323 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800324 adminAnotherPackage.getPackageName()),
325 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800326 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
327 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
328 }
329
330 public void testLoadAdminData_noAdmins() throws Exception {
331 final int ANOTHER_USER_ID = 15;
332 getServices().addUser(ANOTHER_USER_ID, 0);
333
334 initializeDpms();
335
336 // Verify
337 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
338 null, DpmMockContext.CALLER_USER_HANDLE);
339 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
340 null, ANOTHER_USER_ID);
341 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
342 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800343 }
344
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700345 /**
346 * Caller doesn't have proper permissions.
347 */
348 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700349 // 1. Failure cases.
350
351 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100352 assertExpectException(SecurityException.class, /* messageRegex= */ null,
353 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700354
355 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
356 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100357
358 assertExpectException(SecurityException.class, /* messageRegex= */ null,
359 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700360 }
361
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362 /**
363 * Test for:
364 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800365 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700366 * {@link DevicePolicyManager#isAdminActive}
367 * {@link DevicePolicyManager#isAdminActiveAsUser}
368 * {@link DevicePolicyManager#getActiveAdmins}
369 * {@link DevicePolicyManager#getActiveAdminsAsUser}
370 */
371 public void testSetActiveAdmin() throws Exception {
372 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
374
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375 // 2. Call the API.
376 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700377
378 // 3. Verify internal calls.
379
380 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700381 verify(mContext.spiedContext).sendBroadcastAsUser(
382 MockUtils.checkIntentAction(
383 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
384 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
385 verify(mContext.spiedContext).sendBroadcastAsUser(
386 MockUtils.checkIntentAction(
387 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700388 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
389
Pavel Grafov75c0a892017-05-18 17:28:27 +0100390 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700391 eq(admin1.getPackageName()),
392 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
393 eq(PackageManager.DONT_KILL_APP),
394 eq(DpmMockContext.CALLER_USER_HANDLE),
395 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700396
Sudheer Shanka101c3532018-01-08 16:28:42 -0800397 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
398 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
399
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700400 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700401
402 // Make sure it's active admin1.
403 assertTrue(dpm.isAdminActive(admin1));
404 assertFalse(dpm.isAdminActive(admin2));
405 assertFalse(dpm.isAdminActive(admin3));
406
407 // But not admin1 for a different user.
408
409 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
410 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
411 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
412
413 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
414 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
415
416 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
417
418 // Next, add one more admin.
419 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700420 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700421 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700422
423 dpm.setActiveAdmin(admin2, /* replace =*/ false);
424
425 // Now we have two admins.
426 assertTrue(dpm.isAdminActive(admin1));
427 assertTrue(dpm.isAdminActive(admin2));
428 assertFalse(dpm.isAdminActive(admin3));
429
430 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
431 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100432 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700433 eq(admin1.getPackageName()),
434 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
435 eq(PackageManager.DONT_KILL_APP),
436 eq(DpmMockContext.CALLER_USER_HANDLE),
437 anyString());
438
Sudheer Shanka101c3532018-01-08 16:28:42 -0800439 // times(2) because it was previously called for admin1 which is in the same package
440 // as admin2.
441 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
442 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
443
Makoto Onukif76b06a2015-09-22 15:03:44 -0700444 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100445 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
446 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700447
448 // 5. Add the same admin1 again with replace, which should succeed.
449 dpm.setActiveAdmin(admin1, /* replace =*/ true);
450
451 // TODO make sure it's replaced.
452
453 // 6. Test getActiveAdmins()
454 List<ComponentName> admins = dpm.getActiveAdmins();
455 assertEquals(2, admins.size());
456 assertEquals(admin1, admins.get(0));
457 assertEquals(admin2, admins.get(1));
458
Sudheer Shanka101c3532018-01-08 16:28:42 -0800459 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
460 // replaced
461 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
462
Makoto Onukif76b06a2015-09-22 15:03:44 -0700463 // Another user has no admins.
464 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
465
466 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
467 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
468
469 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
470 }
471
Makoto Onukid932f762015-09-29 16:53:38 -0700472 public void testSetActiveAdmin_multiUsers() throws Exception {
473
474 final int ANOTHER_USER_ID = 100;
475 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
476
Pavel Grafov75c0a892017-05-18 17:28:27 +0100477 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700478
479 // Set up pacakge manager for the other user.
480 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700481
482 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
483
484 dpm.setActiveAdmin(admin1, /* replace =*/ false);
485
486 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
487 dpm.setActiveAdmin(admin2, /* replace =*/ false);
488
489
490 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
491 assertTrue(dpm.isAdminActive(admin1));
492 assertFalse(dpm.isAdminActive(admin2));
493
494 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
495 assertFalse(dpm.isAdminActive(admin1));
496 assertTrue(dpm.isAdminActive(admin2));
497 }
498
Makoto Onukif76b06a2015-09-22 15:03:44 -0700499 /**
500 * Test for:
501 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800502 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700503 */
504 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
505 // 1. Make sure the caller has proper permissions.
506 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
507
508 dpm.setActiveAdmin(admin1, /* replace =*/ false);
509 assertTrue(dpm.isAdminActive(admin1));
510
511 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100512 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
513 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700514 }
515
516 /**
517 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800518 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
519 * BIND_DEVICE_ADMIN.
520 */
521 public void testSetActiveAdmin_permissionCheck() throws Exception {
522 // 1. Make sure the caller has proper permissions.
523 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
524
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100525 assertExpectException(IllegalArgumentException.class,
526 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
527 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800528 assertFalse(dpm.isAdminActive(adminNoPerm));
529
530 // Change the target API level to MNC. Now it can be set as DA.
531 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
532 VERSION_CODES.M);
533 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
534 assertTrue(dpm.isAdminActive(adminNoPerm));
535
536 // TODO Test the "load from the file" case where DA will still be loaded even without
537 // BIND_DEVICE_ADMIN and target API is N.
538 }
539
540 /**
541 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700542 * {@link DevicePolicyManager#removeActiveAdmin}
543 */
544 public void testRemoveActiveAdmin_SecurityException() {
545 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
546
547 // Add admin.
548
549 dpm.setActiveAdmin(admin1, /* replace =*/ false);
550
551 assertTrue(dpm.isAdminActive(admin1));
552
553 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
554
555 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100556 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
557 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700558
559 // Try to remove active admin with a different caller userid should fail too, without
560 // having MANAGE_DEVICE_ADMINS.
561 mContext.callerPermissions.clear();
562
Makoto Onukid932f762015-09-29 16:53:38 -0700563 // Change the caller, and call into DPMS directly with a different user-id.
564
Makoto Onukif76b06a2015-09-22 15:03:44 -0700565 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100566 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
567 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700568 }
569
570 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800571 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
572 * (because we can't send the remove broadcast).
573 */
574 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
575 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
576
577 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
578
579 // Add admin.
580
581 dpm.setActiveAdmin(admin1, /* replace =*/ false);
582
583 assertTrue(dpm.isAdminActive(admin1));
584
585 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
586
587 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100588 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800589 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100590 assertExpectException(IllegalStateException.class,
591 /* messageRegex= */ "User must be running and unlocked",
592 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800593
594 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800595 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
596 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800597
598 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100599 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800600 .thenReturn(true);
601
602 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700603 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800604 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
605 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800606 }
607
608 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700609 * Test for:
610 * {@link DevicePolicyManager#removeActiveAdmin}
611 */
Makoto Onukid932f762015-09-29 16:53:38 -0700612 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700613 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
614
615 // Add admin1.
616
617 dpm.setActiveAdmin(admin1, /* replace =*/ false);
618
619 assertTrue(dpm.isAdminActive(admin1));
620 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
621
622 // Different user, but should work, because caller has proper permissions.
623 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700624
625 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700626 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700627
628 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700629 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800630 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
631 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700632
633 // TODO DO Still can't be removed in this case.
634 }
635
636 /**
637 * Test for:
638 * {@link DevicePolicyManager#removeActiveAdmin}
639 */
640 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
641 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
642 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
643
644 // Add admin1.
645
646 dpm.setActiveAdmin(admin1, /* replace =*/ false);
647
648 assertTrue(dpm.isAdminActive(admin1));
649 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
650
651 // Broadcast from saveSettingsLocked().
652 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
653 MockUtils.checkIntentAction(
654 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
655 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
656
657 // Remove. No permissions, but same user, so it'll work.
658 mContext.callerPermissions.clear();
659 dpm.removeActiveAdmin(admin1);
660
Makoto Onukif76b06a2015-09-22 15:03:44 -0700661 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
662 MockUtils.checkIntentAction(
663 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
664 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
665 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700667 eq(dpms.mHandler),
668 eq(Activity.RESULT_OK),
669 isNull(String.class),
670 isNull(Bundle.class));
671
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700672 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800673 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
674 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700675
676 // Again broadcast from saveSettingsLocked().
677 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
678 MockUtils.checkIntentAction(
679 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
680 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
681
682 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700683 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700684
Sudheer Shanka101c3532018-01-08 16:28:42 -0800685 public void testRemoveActiveAdmin_multipleAdminsInUser() {
686 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
687 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
688
689 // Add admin1.
690 dpm.setActiveAdmin(admin1, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin1));
693 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Add admin2.
696 dpm.setActiveAdmin(admin2, /* replace =*/ false);
697
698 assertTrue(dpm.isAdminActive(admin2));
699 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
700
701 // Broadcast from saveSettingsLocked().
702 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
703 MockUtils.checkIntentAction(
704 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
705 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
706
707 // Remove. No permissions, but same user, so it'll work.
708 mContext.callerPermissions.clear();
709 dpm.removeActiveAdmin(admin1);
710
711 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
712 MockUtils.checkIntentAction(
713 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
714 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
715 isNull(String.class),
716 any(BroadcastReceiver.class),
717 eq(dpms.mHandler),
718 eq(Activity.RESULT_OK),
719 isNull(String.class),
720 isNull(Bundle.class));
721
722 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
723 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800724 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800725 eq(DpmMockContext.CALLER_USER_HANDLE));
726
727 // Again broadcast from saveSettingsLocked().
728 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
729 MockUtils.checkIntentAction(
730 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
731 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
732 }
733
734 /**
735 * Test for:
736 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
737 */
738 public void testForceRemoveActiveAdmin() throws Exception {
739 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
740
741 // Add admin.
742 setupPackageInPackageManager(admin1.getPackageName(),
743 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
744 /* appId= */ 10138,
745 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
746 dpm.setActiveAdmin(admin1, /* replace =*/ false);
747 assertTrue(dpm.isAdminActive(admin1));
748
749 // Calling from a non-shell uid should fail with a SecurityException
750 mContext.binder.callingUid = 123456;
751 assertExpectException(SecurityException.class,
752 /* messageRegex =*/ "Non-shell user attempted to call",
753 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
754
755 mContext.binder.callingUid = Process.SHELL_UID;
756 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
757
758 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
759 // Verify
760 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
761 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
762 null, DpmMockContext.CALLER_USER_HANDLE);
763 }
764
Makoto Onukib643fb02015-09-22 15:03:44 -0700765 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000766 * Test for: @{link DevicePolicyManager#setActivePasswordState}
767 *
768 * Validates that when the password for a user changes, the notification broadcast intent
769 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
770 * addition to ones in the original user.
771 */
772 public void testSetActivePasswordState_sendToProfiles() throws Exception {
773 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
774
775 final int MANAGED_PROFILE_USER_ID = 78;
776 final int MANAGED_PROFILE_ADMIN_UID =
777 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
778
779 // Setup device owner.
780 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
781 mContext.packageName = admin1.getPackageName();
782 setupDeviceOwner();
783
784 // Add a managed profile belonging to the system user.
785 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
786
787 // Change the parent user's password.
788 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
789
790 // Both the device owner and the managed profile owner should receive this broadcast.
791 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
792 intent.setComponent(admin1);
793 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
794
795 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
796 MockUtils.checkIntent(intent),
797 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
798 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
799 MockUtils.checkIntent(intent),
800 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
801 }
802
803 /**
804 * Test for: @{link DevicePolicyManager#setActivePasswordState}
805 *
806 * Validates that when the password for a managed profile changes, the notification broadcast
807 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
808 * its parent.
809 */
810 public void testSetActivePasswordState_notSentToParent() throws Exception {
811 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
812
813 final int MANAGED_PROFILE_USER_ID = 78;
814 final int MANAGED_PROFILE_ADMIN_UID =
815 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
816
817 // Setup device owner.
818 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
819 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100820 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000821 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
822 setupDeviceOwner();
823
824 // Add a managed profile belonging to the system user.
825 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
826
827 // Change the profile's password.
828 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
829
830 // Both the device owner and the managed profile owner should receive this broadcast.
831 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
832 intent.setComponent(admin1);
833 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
834
835 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
836 MockUtils.checkIntent(intent),
837 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
838 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
839 MockUtils.checkIntent(intent),
840 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
841 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100842
Robin Leed2a73ed2016-12-19 09:07:16 +0000843 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000844 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700845 */
846 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000847 setDeviceOwner();
848
849 // Try to set a profile owner on the same user, which should fail.
850 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
851 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100852 assertExpectException(IllegalStateException.class,
853 /* messageRegex= */ "already has a device owner",
854 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000855
856 // DO admin can't be deactivated.
857 dpm.removeActiveAdmin(admin1);
858 assertTrue(dpm.isAdminActive(admin1));
859
860 // TODO Test getDeviceOwnerName() too. To do so, we need to change
861 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
862 }
863
864 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700865 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800866 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
868 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
869
Makoto Onukid932f762015-09-29 16:53:38 -0700870 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700871 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
872
Makoto Onukid932f762015-09-29 16:53:38 -0700873 // Make sure admin1 is installed on system user.
874 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700875
Makoto Onukic8a5a552015-11-19 14:29:12 -0800876 // Check various get APIs.
877 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
878
Makoto Onukib643fb02015-09-22 15:03:44 -0700879 // DO needs to be an DA.
880 dpm.setActiveAdmin(admin1, /* replace =*/ false);
881
882 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700883 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700884
Makoto Onukic8a5a552015-11-19 14:29:12 -0800885 // getDeviceOwnerComponent should return the admin1 component.
886 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
887 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
888
889 // Check various get APIs.
890 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
891
892 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
893 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
894 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
895 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
896
897 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
898
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000899 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100900 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000901 eq(admin1.getPackageName()));
902
Makoto Onukib643fb02015-09-22 15:03:44 -0700903 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100904 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700905 eq(UserHandle.USER_SYSTEM), eq(false));
906
907 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
908 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
909 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
910
Makoto Onukic8a5a552015-11-19 14:29:12 -0800911 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700912 }
913
Makoto Onukic8a5a552015-11-19 14:29:12 -0800914 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
915 final int origCallingUser = mContext.binder.callingUid;
916 final List origPermissions = new ArrayList(mContext.callerPermissions);
917 mContext.callerPermissions.clear();
918
919 mContext.callerPermissions.add(permission.MANAGE_USERS);
920
921 mContext.binder.callingUid = Process.SYSTEM_UID;
922
923 // TODO Test getDeviceOwnerName() too. To do so, we need to change
924 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
925 if (hasDeviceOwner) {
926 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
927 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
928 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
929
930 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
931 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
932 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
933 } else {
934 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
935 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
936 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
937
938 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
939 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
940 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
941 }
942
943 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
944 if (hasDeviceOwner) {
945 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
946 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
947 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
948
949 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
950 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
951 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
952 } else {
953 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
954 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
955 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
956
957 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
958 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
959 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
960 }
961
962 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
963 // Still with MANAGE_USERS.
964 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
965 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
966 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
967
968 if (hasDeviceOwner) {
969 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
970 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
971 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
972 } else {
973 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
974 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
975 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
976 }
977
978 mContext.binder.callingUid = Process.SYSTEM_UID;
979 mContext.callerPermissions.remove(permission.MANAGE_USERS);
980 // System can still call "OnAnyUser" without MANAGE_USERS.
981 if (hasDeviceOwner) {
982 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
983 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
984 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
985
986 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
987 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
988 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
989 } else {
990 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
991 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
992 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
993
994 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
995 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
996 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
997 }
998
999 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1000 // Still no MANAGE_USERS.
1001 if (hasDeviceOwner) {
1002 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1003 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1004 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1005 } else {
1006 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1007 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1008 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1009 }
1010
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001011 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1012 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1013 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1014 dpm::getDeviceOwnerComponentOnAnyUser);
1015 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1016 dpm::getDeviceOwnerUserId);
1017 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1018 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001019
1020 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1021 // Still no MANAGE_USERS.
1022 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1023 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1024 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1025
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001026 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1027 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1028 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1029 dpm::getDeviceOwnerComponentOnAnyUser);
1030 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1031 dpm::getDeviceOwnerUserId);
1032 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1033 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001034
1035 // Restore.
1036 mContext.binder.callingUid = origCallingUser;
1037 mContext.callerPermissions.addAll(origPermissions);
1038 }
1039
1040
Makoto Onukib643fb02015-09-22 15:03:44 -07001041 /**
1042 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1043 */
1044 public void testSetDeviceOwner_noSuchPackage() {
1045 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001046 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001047 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1048 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1049
1050 // Call from a process on the system user.
1051 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1052
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001053 assertExpectException(IllegalArgumentException.class,
1054 /* messageRegex= */ "Invalid component",
1055 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001056 }
1057
1058 public void testSetDeviceOwner_failures() throws Exception {
1059 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1060 }
1061
Makoto Onukia52562c2015-10-01 16:12:31 -07001062 public void testClearDeviceOwner() throws Exception {
1063 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001064 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001065 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1066 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1067
1068 // Set admin1 as a DA to the secondary user.
1069 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1070
1071 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1072
1073 // Set admin 1 as the DO to the system user.
1074
1075 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1076 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1077 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1078 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1079
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001080 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001081 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001082 eq(admin1.getPackageName()));
1083
Makoto Onukic8a5a552015-11-19 14:29:12 -08001084 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001085
Makoto Onuki90b89652016-01-28 14:44:18 -08001086 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001087 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001088 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001089
1090 assertTrue(dpm.isAdminActive(admin1));
1091 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1092
Makoto Onukia52562c2015-10-01 16:12:31 -07001093 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001094 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001095
1096 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001097 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1098 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001099
1100 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001101 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001102 assertExpectException(IllegalStateException.class,
1103 /* messageRegex= */ "User must be running and unlocked",
1104 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001105
Pavel Grafov75c0a892017-05-18 17:28:27 +01001106 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1107 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001108 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1109
1110 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001111 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001112
Pavel Grafov75c0a892017-05-18 17:28:27 +01001113 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001114 eq(false),
1115 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1116
Pavel Grafov75c0a892017-05-18 17:28:27 +01001117 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001118 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001119 eq(null),
1120 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001121
Sudheer Shanka101c3532018-01-08 16:28:42 -08001122 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1123 null, UserHandle.USER_SYSTEM);
1124
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001125 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001126
1127 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1128 // and once for clearing it.
1129 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1130 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1131 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001132 // TODO Check other calls.
1133 }
1134
1135 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1136 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001137 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001138 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1139 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1140
1141 // Set admin1 as a DA to the secondary user.
1142 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1143
1144 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1145
1146 // Set admin 1 as the DO to the system user.
1147
1148 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1149 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1150 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1151 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1152
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001153 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001154 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001155 eq(admin1.getPackageName()));
1156
Makoto Onukic8a5a552015-11-19 14:29:12 -08001157 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001158
1159 // Now call clear from the secondary user, which should throw.
1160 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1161
1162 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001163 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001164 eq(admin1.getPackageName()),
1165 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001166 assertExpectException(SecurityException.class,
1167 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1168 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001169
Makoto Onukic8a5a552015-11-19 14:29:12 -08001170 // DO shouldn't be removed.
1171 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001172 }
1173
Makoto Onukib643fb02015-09-22 15:03:44 -07001174 public void testSetProfileOwner() throws Exception {
1175 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001176
Makoto Onuki90b89652016-01-28 14:44:18 -08001177 // PO admin can't be deactivated.
1178 dpm.removeActiveAdmin(admin1);
1179 assertTrue(dpm.isAdminActive(admin1));
1180
Makoto Onuki803d6752015-10-30 12:58:39 -07001181 // Try setting DO on the same user, which should fail.
1182 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001183 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1184 runAsCaller(mServiceContext, dpms, dpm -> {
1185 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001186 assertExpectException(IllegalStateException.class,
1187 /* messageRegex= */ "already has a profile owner",
1188 () -> dpm.setDeviceOwner(admin2, "owner-name",
1189 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001190 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001191 }
1192
Makoto Onuki90b89652016-01-28 14:44:18 -08001193 public void testClearProfileOwner() throws Exception {
1194 setAsProfileOwner(admin1);
1195
1196 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1197
1198 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1199 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1200
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001201 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001202 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001203 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001204 assertExpectException(IllegalStateException.class,
1205 /* messageRegex= */ "User must be running and unlocked",
1206 () -> dpm.clearProfileOwner(admin1));
1207
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001208 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001209 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001210 dpm.clearProfileOwner(admin1);
1211
1212 // Check
1213 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001214 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001215 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1216 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001217 }
1218
Makoto Onukib643fb02015-09-22 15:03:44 -07001219 public void testSetProfileOwner_failures() throws Exception {
1220 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1221 }
1222
Makoto Onukia52562c2015-10-01 16:12:31 -07001223 public void testGetDeviceOwnerAdminLocked() throws Exception {
1224 checkDeviceOwnerWithMultipleDeviceAdmins();
1225 }
1226
1227 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1228 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1229 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1230 // make sure it gets the right component from the right user.
1231
1232 final int ANOTHER_USER_ID = 100;
1233 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1234
Pavel Grafov75c0a892017-05-18 17:28:27 +01001235 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001236
1237 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001238 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001239 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1240 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1241
1242 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1243
Pavel Grafov75c0a892017-05-18 17:28:27 +01001244 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001245
Makoto Onukia52562c2015-10-01 16:12:31 -07001246 // Make sure the admin packge is installed to each user.
1247 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1248 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1249
1250 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1251 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1252
1253 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1254
1255
1256 // Set active admins to the users.
1257 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1258 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1259
1260 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1261 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1262
1263 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1264
1265 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001266 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001267 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1268
Makoto Onukic8a5a552015-11-19 14:29:12 -08001269 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001270
1271 // Then check getDeviceOwnerAdminLocked().
1272 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1273 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1274 }
1275
1276 /**
1277 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001278 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1279 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001280 *
1281 * We didn't use to persist the DO component class name, but now we do, and the above method
1282 * finds the right component from a package name upon migration.
1283 */
1284 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001285 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001286 checkDeviceOwnerWithMultipleDeviceAdmins();
1287
1288 // Overwrite the device owner setting and clears the clas name.
1289 dpms.mOwners.setDeviceOwner(
1290 new ComponentName(admin2.getPackageName(), ""),
1291 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1292 dpms.mOwners.writeDeviceOwner();
1293
1294 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001295 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001296
1297 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001298 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001299 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001300 initializeDpms();
1301
1302 // Now the DO component name is a full name.
1303 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1304 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001305 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001306 }
1307
Makoto Onukib643fb02015-09-22 15:03:44 -07001308 public void testSetGetApplicationRestriction() {
1309 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001310 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001311
1312 {
1313 Bundle rest = new Bundle();
1314 rest.putString("KEY_STRING", "Foo1");
1315 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1316 }
1317
1318 {
1319 Bundle rest = new Bundle();
1320 rest.putString("KEY_STRING", "Foo2");
1321 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1322 }
1323
1324 {
1325 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1326 assertNotNull(returned);
1327 assertEquals(returned.size(), 1);
1328 assertEquals(returned.get("KEY_STRING"), "Foo1");
1329 }
1330
1331 {
1332 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1333 assertNotNull(returned);
1334 assertEquals(returned.size(), 1);
1335 assertEquals(returned.get("KEY_STRING"), "Foo2");
1336 }
1337
1338 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1339 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1340 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001341
Edman Anjosf9946772016-11-28 16:35:15 +01001342 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001343 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1344 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001345 *
1346 * @param packageName the name of the package to be setup
1347 * @param appId the application ID to be given to the package
1348 * @return the UID of the package as known by the mock package manager
1349 */
1350 private int setupPackageInPackageManager(final String packageName, final int appId)
1351 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001352 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001353 ApplicationInfo.FLAG_HAS_CODE);
1354 }
1355
1356 /**
1357 * Setup a package in the package manager mock. Useful for faking installed applications.
1358 *
1359 * @param packageName the name of the package to be setup
1360 * @param userId the user id where the package will be "installed"
1361 * @param appId the application ID to be given to the package
1362 * @param flags flags to set in the ApplicationInfo for this package
1363 * @return the UID of the package as known by the mock package manager
1364 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001365 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1366 int flags) throws Exception {
1367 final int uid = UserHandle.getUid(userId, appId);
1368 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001369 final PackageInfo pi = new PackageInfo();
1370 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001371 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001372 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001373 eq(packageName),
1374 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001375 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001376 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001377 eq(packageName),
1378 anyInt(),
1379 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001380 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001381 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001383 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001384 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001385 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001386 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001387 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001388 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001389 return uid;
1390 }
1391
Robin Lee7f5c91c2017-02-08 21:27:02 +00001392 public void testCertificateDisclosure() throws Exception {
1393 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1394 final UserHandle user = UserHandle.of(userId);
1395
1396 mContext.applicationInfo = new ApplicationInfo();
1397 mContext.callerPermissions.add(permission.MANAGE_USERS);
1398 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001399 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001400 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1401
Robin Leeabaa0692017-02-20 20:54:22 +00001402 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1403 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001404
1405 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1406 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1407
1408 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001409 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001410 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001411 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001412 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001413 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001414 .cancelAsUser(anyString(), anyInt(), eq(user));
1415
1416 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001417 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001418 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001419 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1420 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001421 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001422 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001423 .notifyAsUser(anyString(), anyInt(), argThat(
1424 new BaseMatcher<Notification>() {
1425 @Override
1426 public boolean matches(Object item) {
1427 final Notification noti = (Notification) item;
1428 return TEST_STRING.equals(
1429 noti.extras.getString(Notification.EXTRA_TITLE));
1430 }
1431 @Override
1432 public void describeTo(Description description) {
1433 description.appendText(
1434 "Notification{title=\"" + TEST_STRING + "\"}");
1435 }
1436 }), eq(user));
1437 }
1438
Edman Anjosf9946772016-11-28 16:35:15 +01001439 /**
1440 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1441 * privileges can acually be exercised by a delegate are not covered here.
1442 */
1443 public void testDelegation() throws Exception {
1444 setAsProfileOwner(admin1);
1445
1446 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1447
1448 // Given two packages
1449 final String CERT_DELEGATE = "com.delegate.certs";
1450 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1451 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1452 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1453 20989);
1454
1455 // On delegation
1456 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1457 mContext.packageName = admin1.getPackageName();
1458 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1459 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1460
1461 // DPMS correctly stores and retrieves the delegates
1462 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1463 assertEquals(2, policy.mDelegationMap.size());
1464 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1465 DELEGATION_CERT_INSTALL);
1466 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1467 DELEGATION_CERT_INSTALL);
1468 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1469 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1470 DELEGATION_APP_RESTRICTIONS);
1471 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1472 DELEGATION_APP_RESTRICTIONS);
1473 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1474
1475 // On calling install certificate APIs from an unauthorized process
1476 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1477 mContext.packageName = RESTRICTIONS_DELEGATE;
1478
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001479 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1480 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001481
1482 // On calling install certificate APIs from an authorized process
1483 mContext.binder.callingUid = CERT_DELEGATE_UID;
1484 mContext.packageName = CERT_DELEGATE;
1485
1486 // DPMS executes without a SecurityException
1487 try {
1488 dpm.installCaCert(null, null);
1489 } catch (SecurityException unexpected) {
1490 fail("Threw SecurityException on authorized access");
1491 } catch (NullPointerException expected) {
1492 }
1493
1494 // On removing a delegate
1495 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1496 mContext.packageName = admin1.getPackageName();
1497 dpm.setCertInstallerPackage(admin1, null);
1498
1499 // DPMS does not allow access to ex-delegate
1500 mContext.binder.callingUid = CERT_DELEGATE_UID;
1501 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001502 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1503 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001504
1505 // But still allows access to other existing delegates
1506 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1507 mContext.packageName = RESTRICTIONS_DELEGATE;
1508 try {
1509 dpm.getApplicationRestrictions(null, "pkg");
1510 } catch (SecurityException expected) {
1511 fail("Threw SecurityException on authorized access");
1512 }
1513 }
1514
Esteban Talaverabf60f722015-12-10 16:26:44 +00001515 public void testApplicationRestrictionsManagingApp() throws Exception {
1516 setAsProfileOwner(admin1);
1517
Rubin Xued1928a2016-02-11 17:23:06 +00001518 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001519 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001520 final String nonDelegateExceptionMessageRegex =
1521 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001522 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001523 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1524 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001525
Esteban Talaverabf60f722015-12-10 16:26:44 +00001526 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1527 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001528 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1529 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001530 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001531 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001533 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1534 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001535
1536 // Check via the profile owner that no restrictions were set.
1537 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001538 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001539 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1540
Rubin Xued1928a2016-02-11 17:23:06 +00001541 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001542 assertExpectException(PackageManager.NameNotFoundException.class,
1543 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1544 () -> dpm.setApplicationRestrictionsManagingPackage(
1545 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001546
Esteban Talaverabf60f722015-12-10 16:26:44 +00001547 // Let appRestrictionsManagerPackage manage app restrictions
1548 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1549 assertEquals(appRestrictionsManagerPackage,
1550 dpm.getApplicationRestrictionsManagingPackage(admin1));
1551
1552 // Now that package should be able to set and retrieve app restrictions.
1553 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001554 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001555 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1556 dpm.setApplicationRestrictions(null, "pkg1", rest);
1557 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1558 assertEquals(1, returned.size(), 1);
1559 assertEquals("Foo1", returned.get("KEY_STRING"));
1560
1561 // The same app running on a separate user shouldn't be able to manage app restrictions.
1562 mContext.binder.callingUid = UserHandle.getUid(
1563 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1564 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001565 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1566 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001567
1568 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1569 // too.
1570 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001571 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001572 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1573 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1574 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1575
1576 // Removing the ability for the package to manage app restrictions.
1577 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1578 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1579 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001580 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001581 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001582 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1583 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001584 }
1585
Makoto Onukia4f11972015-10-01 13:19:58 -07001586 public void testSetUserRestriction_asDo() throws Exception {
1587 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001588 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001589 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1590 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1591
1592 // First, set DO.
1593
1594 // Call from a process on the system user.
1595 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1596
1597 // Make sure admin1 is installed on system user.
1598 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001599
1600 // Call.
1601 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001602 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001603 UserHandle.USER_SYSTEM));
1604
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001605 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001606 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001607 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001608 DpmTestUtils.assertRestrictions(
1609 DpmTestUtils.newRestrictions(defaultRestrictions),
1610 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1611 );
1612 DpmTestUtils.assertRestrictions(
1613 DpmTestUtils.newRestrictions(defaultRestrictions),
1614 dpm.getUserRestrictions(admin1)
1615 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001616 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001617 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001618 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001619 eq(true) /* isDeviceOwner */,
1620 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001621 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001622 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001623
1624 for (String restriction : defaultRestrictions) {
1625 dpm.clearUserRestriction(admin1, restriction);
1626 }
1627
Esteban Talavera548a04b2016-12-20 15:22:30 +00001628 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001629 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001630
1631 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001632 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1635 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001636 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001637
Makoto Onukia4f11972015-10-01 13:19:58 -07001638 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001639 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001641 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1642 UserManager.DISALLOW_ADD_USER),
1643 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001644 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001645
Makoto Onuki068c54a2015-10-13 14:34:03 -07001646 DpmTestUtils.assertRestrictions(
1647 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001648 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001649 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1650 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001651 DpmTestUtils.assertRestrictions(
1652 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001654 dpm.getUserRestrictions(admin1)
1655 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001656
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001658 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001659 eq(UserHandle.USER_SYSTEM),
1660 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001661 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001662 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001663
Makoto Onuki068c54a2015-10-13 14:34:03 -07001664 DpmTestUtils.assertRestrictions(
1665 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1666 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1667 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001668 DpmTestUtils.assertRestrictions(
1669 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1670 dpm.getUserRestrictions(admin1)
1671 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001672
1673 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001674 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001675 eq(UserHandle.USER_SYSTEM),
1676 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001677 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001678 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001679
Esteban Talavera548a04b2016-12-20 15:22:30 +00001680 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001681
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1683 // DO sets them, the scope is global.
1684 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001686 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001687 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001688 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001690 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1691 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001692 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001693
1694 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1695 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697
1698 // More tests.
1699 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001700 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001701 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1703 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001704 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001705
1706 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001707 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001708 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001709 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001710 UserManager.DISALLOW_ADD_USER),
1711 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001712 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713
1714 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001715 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 eq(UserHandle.USER_SYSTEM),
1717 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 UserManager.DISALLOW_ADD_USER),
1720 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001721 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001722 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723
Eric Sandnessca5969d2018-08-10 13:28:46 +01001724 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1725 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1726 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727
Eric Sandnessca5969d2018-08-10 13:28:46 +01001728 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1729 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001730
Eric Sandnessca5969d2018-08-10 13:28:46 +01001731 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1732 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1733 () -> dpm.setCameraDisabled(admin1, true));
1734 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1735
1736 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1737 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1738 () -> dpm.setKeyguardDisabledFeatures(admin1,
1739 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1740 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1741
1742 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1743 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1744 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1745 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1746
1747 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1748 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1749 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1750 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001751 }
1752
1753 public void testSetUserRestriction_asPo() {
1754 setAsProfileOwner(admin1);
1755
Makoto Onuki068c54a2015-10-13 14:34:03 -07001756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(),
1758 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1759 .ensureUserRestrictions()
1760 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001761
1762 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001763 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 eq(DpmMockContext.CALLER_USER_HANDLE),
1765 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001766 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768
Makoto Onukia4f11972015-10-01 13:19:58 -07001769 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001770 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001771 eq(DpmMockContext.CALLER_USER_HANDLE),
1772 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1773 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001774 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001775 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001776
Makoto Onuki068c54a2015-10-13 14:34:03 -07001777 DpmTestUtils.assertRestrictions(
1778 DpmTestUtils.newRestrictions(
1779 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1780 UserManager.DISALLOW_OUTGOING_CALLS
1781 ),
1782 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1783 .ensureUserRestrictions()
1784 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001785 DpmTestUtils.assertRestrictions(
1786 DpmTestUtils.newRestrictions(
1787 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1788 UserManager.DISALLOW_OUTGOING_CALLS
1789 ),
1790 dpm.getUserRestrictions(admin1)
1791 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001792
1793 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001794 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795 eq(DpmMockContext.CALLER_USER_HANDLE),
1796 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001797 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001798 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001799
1800 DpmTestUtils.assertRestrictions(
1801 DpmTestUtils.newRestrictions(
1802 UserManager.DISALLOW_OUTGOING_CALLS
1803 ),
1804 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1805 .ensureUserRestrictions()
1806 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001807 DpmTestUtils.assertRestrictions(
1808 DpmTestUtils.newRestrictions(
1809 UserManager.DISALLOW_OUTGOING_CALLS
1810 ),
1811 dpm.getUserRestrictions(admin1)
1812 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001813
1814 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001815 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001816 eq(DpmMockContext.CALLER_USER_HANDLE),
1817 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001818 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001819 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001820
Makoto Onuki068c54a2015-10-13 14:34:03 -07001821 DpmTestUtils.assertRestrictions(
1822 DpmTestUtils.newRestrictions(),
1823 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1824 .ensureUserRestrictions()
1825 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001826 DpmTestUtils.assertRestrictions(
1827 DpmTestUtils.newRestrictions(),
1828 dpm.getUserRestrictions(admin1)
1829 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001830
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1832 // though when DO sets them they'll be applied globally.
1833 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001834 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001835 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001836 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001837 eq(DpmMockContext.CALLER_USER_HANDLE),
1838 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1839 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001840 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001841 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001842
1843 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001844 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001846 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001848 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001849 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001850
Makoto Onukia4f11972015-10-01 13:19:58 -07001851 // TODO Make sure restrictions are written to the file.
1852 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001853
Esteban Talavera548a04b2016-12-20 15:22:30 +00001854
1855 public void testDefaultEnabledUserRestrictions() throws Exception {
1856 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1857 mContext.callerPermissions.add(permission.MANAGE_USERS);
1858 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1859 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1860
1861 // First, set DO.
1862
1863 // Call from a process on the system user.
1864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1865
1866 // Make sure admin1 is installed on system user.
1867 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1868
1869 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1870 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1871 UserHandle.USER_SYSTEM));
1872
1873 // Check that the user restrictions that are enabled by default are set. Then unset them.
1874 String[] defaultRestrictions = UserRestrictionsUtils
1875 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1876 assertTrue(defaultRestrictions.length > 0);
1877 DpmTestUtils.assertRestrictions(
1878 DpmTestUtils.newRestrictions(defaultRestrictions),
1879 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1880 );
1881 DpmTestUtils.assertRestrictions(
1882 DpmTestUtils.newRestrictions(defaultRestrictions),
1883 dpm.getUserRestrictions(admin1)
1884 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001885 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001886 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001887 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001888 eq(true) /* isDeviceOwner */,
1889 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001890 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001891 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001892
1893 for (String restriction : defaultRestrictions) {
1894 dpm.clearUserRestriction(admin1, restriction);
1895 }
1896
1897 assertNoDeviceOwnerRestrictions();
1898
1899 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001900 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001901 initializeDpms();
1902 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1903 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1904
1905 assertNoDeviceOwnerRestrictions();
1906
1907 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1908 // is set as it wasn't enabled during setDeviceOwner.
1909 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1910 assertFalse(UserRestrictionsUtils
1911 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1912 UserRestrictionsUtils
1913 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1914 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001915 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001916 initializeDpms();
1917 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1918 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1919
1920 DpmTestUtils.assertRestrictions(
1921 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1922 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1923 );
1924 DpmTestUtils.assertRestrictions(
1925 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1926 dpm.getUserRestrictions(admin1)
1927 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001928 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001929 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001930 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001931 eq(true) /* isDeviceOwner */,
1932 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001933 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001934 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001935
1936 // Remove the restriction.
1937 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1938
1939 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1940 initializeDpms();
1941 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1942 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1943 assertNoDeviceOwnerRestrictions();
1944 } finally {
1945 UserRestrictionsUtils
1946 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1947 }
1948 }
1949
1950 private void assertNoDeviceOwnerRestrictions() {
1951 DpmTestUtils.assertRestrictions(
1952 DpmTestUtils.newRestrictions(),
1953 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1954 );
1955 DpmTestUtils.assertRestrictions(
1956 DpmTestUtils.newRestrictions(),
1957 dpm.getUserRestrictions(admin1)
1958 );
1959 }
1960
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001961 public void testGetMacAddress() throws Exception {
1962 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1963 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1964 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1965
1966 // In this test, change the caller user to "system".
1967 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1968
1969 // Make sure admin1 is installed on system user.
1970 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1971
1972 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001973 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1974 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001975
1976 // DO needs to be an DA.
1977 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1978 assertTrue(dpm.isAdminActive(admin1));
1979
1980 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001981 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1982 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001983
1984 // Test 3. Caller has PO, but not DO.
1985 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001986 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1987 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001988
1989 // Remove PO.
1990 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001991 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001992 // Test 4, Caller is DO now.
1993 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1994
xshu425b9a62018-12-13 14:18:18 -08001995 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001996 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001997
xshu425b9a62018-12-13 14:18:18 -08001998 // 4-2. When WifiManager returns an empty array, dpm should also output null.
1999 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002000 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002001
2002 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002003 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2004 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002005 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002006 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002007
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002008 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002009 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2010 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2011
2012 // In this test, change the caller user to "system".
2013 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2014
2015 // Make sure admin1 is installed on system user.
2016 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2017
2018 // Set admin1 as DA.
2019 dpm.setActiveAdmin(admin1, false);
2020 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002021 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2022 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002023
2024 // Set admin1 as PO.
2025 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002026 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2027 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002028
2029 // Remove PO and add DO.
2030 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002031 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002032 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2033
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002034 // admin1 is DO.
2035 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002036 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002037 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002038 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2039 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002040
2041 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002042 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002043 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002044 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2045 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002046
2047 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002048 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002049 dpm.reboot(admin1);
2050 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002051
2052 public void testSetGetSupportText() {
2053 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2054 dpm.setActiveAdmin(admin1, true);
2055 dpm.setActiveAdmin(admin2, true);
2056 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2057
2058 // Null default support messages.
2059 {
2060 assertNull(dpm.getLongSupportMessage(admin1));
2061 assertNull(dpm.getShortSupportMessage(admin1));
2062 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2063 assertNull(dpm.getShortSupportMessageForUser(admin1,
2064 DpmMockContext.CALLER_USER_HANDLE));
2065 assertNull(dpm.getLongSupportMessageForUser(admin1,
2066 DpmMockContext.CALLER_USER_HANDLE));
2067 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2068 }
2069
2070 // Only system can call the per user versions.
2071 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002072 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2073 () -> dpm.getShortSupportMessageForUser(admin1,
2074 DpmMockContext.CALLER_USER_HANDLE));
2075 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2076 () -> dpm.getLongSupportMessageForUser(admin1,
2077 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002078 }
2079
2080 // Can't set message for admin in another uid.
2081 {
2082 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002083 assertExpectException(SecurityException.class,
2084 /* messageRegex= */ "is not owned by uid",
2085 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002086 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2087 }
2088
2089 // Set/Get short returns what it sets and other admins text isn't changed.
2090 {
2091 final String supportText = "Some text to test with.";
2092 dpm.setShortSupportMessage(admin1, supportText);
2093 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2094 assertNull(dpm.getLongSupportMessage(admin1));
2095 assertNull(dpm.getShortSupportMessage(admin2));
2096
2097 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2098 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2099 DpmMockContext.CALLER_USER_HANDLE));
2100 assertNull(dpm.getShortSupportMessageForUser(admin2,
2101 DpmMockContext.CALLER_USER_HANDLE));
2102 assertNull(dpm.getLongSupportMessageForUser(admin1,
2103 DpmMockContext.CALLER_USER_HANDLE));
2104 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2105
2106 dpm.setShortSupportMessage(admin1, null);
2107 assertNull(dpm.getShortSupportMessage(admin1));
2108 }
2109
2110 // Set/Get long returns what it sets and other admins text isn't changed.
2111 {
2112 final String supportText = "Some text to test with.\nWith more text.";
2113 dpm.setLongSupportMessage(admin1, supportText);
2114 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2115 assertNull(dpm.getShortSupportMessage(admin1));
2116 assertNull(dpm.getLongSupportMessage(admin2));
2117
2118 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2119 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2120 DpmMockContext.CALLER_USER_HANDLE));
2121 assertNull(dpm.getLongSupportMessageForUser(admin2,
2122 DpmMockContext.CALLER_USER_HANDLE));
2123 assertNull(dpm.getShortSupportMessageForUser(admin1,
2124 DpmMockContext.CALLER_USER_HANDLE));
2125 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2126
2127 dpm.setLongSupportMessage(admin1, null);
2128 assertNull(dpm.getLongSupportMessage(admin1));
2129 }
2130 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002131
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002132 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002133 setAsProfileOwner(admin1);
2134
2135 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002136 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002137
2138 // Setup
2139 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2140 final String package1 = "com.example.one";
2141 final String package2 = "com.example.two";
2142 pkgsToRestrict.add(package1);
2143 pkgsToRestrict.add(package2);
2144 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2145 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002146 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002147
2148 // Verify
2149 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002150 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002151 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2152 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2153 eq(DpmMockContext.CALLER_USER_HANDLE));
2154
2155 // Setup
2156 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002157 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002158
2159 // Verify
2160 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002161 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002162 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2163 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2164 eq(DpmMockContext.CALLER_USER_HANDLE));
2165 }
2166
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002167 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002168 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2169 dpm.setActiveAdmin(admin1, true);
2170 assertTrue(dpm.isAdminActive(admin1));
2171 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2172
2173 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002174 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002175 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002176 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002177 }
2178
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002179 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002180 setAsProfileOwner(admin1);
2181
2182 // Setup
2183 final ArrayList<String> emptyList = new ArrayList<>();
2184 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2185 final String package1 = "com.example.one";
2186 final String package2 = "com.example.two";
2187 final String package3 = "com.example.three";
2188 pkgsToRestrict.add(package1);
2189 pkgsToRestrict.add(package2);
2190 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2191 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002192 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002193
2194 // Verify
2195 assertEquals(emptyList, excludedPkgs);
2196 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2197 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002198 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002199 DpmMockContext.CALLER_USER_HANDLE));
2200 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002201 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002202 DpmMockContext.CALLER_USER_HANDLE));
2203 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002204 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002205 DpmMockContext.CALLER_USER_HANDLE));
2206 }
2207
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002208 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002209 setAsProfileOwner(admin1);
2210 assertExpectException(SecurityException.class,
2211 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002212 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002213 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2214 dpm.clearProfileOwner(admin1);
2215
2216 setDeviceOwner();
2217 assertExpectException(SecurityException.class,
2218 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002219 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002220 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2221 clearDeviceOwner();
2222 }
2223
phweiss73145f42017-01-17 19:06:38 +01002224 public void testCreateAdminSupportIntent() throws Exception {
2225 // Setup device owner.
2226 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2227 setupDeviceOwner();
2228
2229 // Nonexisting permission returns null
2230 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2231 assertNull(intent);
2232
2233 // Existing permission that is not set returns null
2234 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2235 assertNull(intent);
2236
2237 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002238 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002239 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2240 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2241 .thenReturn(true);
2242 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2243 assertNull(intent);
2244
2245 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002246 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002247 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2248 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2249 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2250 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2251 assertNotNull(intent);
2252 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2253 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2254 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002255 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002256 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2257 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2258
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002259 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2260 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002261
2262 // Camera is not disabled
2263 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2264 assertNull(intent);
2265
2266 // Camera is disabled
2267 dpm.setCameraDisabled(admin1, true);
2268 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2269 assertNotNull(intent);
2270 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2271 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2272
2273 // Screen capture is not disabled
2274 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2275 assertNull(intent);
2276
2277 // Screen capture is disabled
2278 dpm.setScreenCaptureDisabled(admin1, true);
2279 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2280 assertNotNull(intent);
2281 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2282 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2283
2284 // Same checks for different user
2285 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2286 // Camera should be disabled by device owner
2287 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2288 assertNotNull(intent);
2289 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2290 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2291 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2292 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2293 // ScreenCapture should not be disabled by device owner
2294 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2295 assertNull(intent);
2296 }
2297
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002298 /**
2299 * Test for:
2300 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002301 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002302 * {@link DevicePolicyManager#isAffiliatedUser}
2303 */
2304 public void testUserAffiliation() throws Exception {
2305 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2306 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2307 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2308
2309 // Check that the system user is unaffiliated.
2310 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2311 assertFalse(dpm.isAffiliatedUser());
2312
2313 // Set a device owner on the system user. Check that the system user becomes affiliated.
2314 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2315 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2316 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2317 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002318 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002319
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002320 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002321 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2322 setAsProfileOwner(admin2);
2323 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002324 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002325
2326 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2327 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002328 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002329 userAffiliationIds.add("red");
2330 userAffiliationIds.add("green");
2331 userAffiliationIds.add("blue");
2332 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002333 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002334 assertFalse(dpm.isAffiliatedUser());
2335
2336 // Have the device owner specify a set of affiliation ids that do not intersect with those
2337 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002338 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002339 deviceAffiliationIds.add("cyan");
2340 deviceAffiliationIds.add("yellow");
2341 deviceAffiliationIds.add("magenta");
2342 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2343 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002344 MoreAsserts.assertContentsInAnyOrder(
2345 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002346 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2347 assertFalse(dpm.isAffiliatedUser());
2348
2349 // Have the profile owner specify a set of affiliation ids that intersect with those
2350 // specified by the device owner. Check that the test user becomes affiliated.
2351 userAffiliationIds.add("yellow");
2352 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002353 MoreAsserts.assertContentsInAnyOrder(
2354 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002355 assertTrue(dpm.isAffiliatedUser());
2356
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002357 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002358 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002359 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002360 assertFalse(dpm.isAffiliatedUser());
2361
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002362 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2363 dpm.setAffiliationIds(admin2, userAffiliationIds);
2364 assertTrue(dpm.isAffiliatedUser());
2365 dpm.clearProfileOwner(admin2);
2366 assertFalse(dpm.isAffiliatedUser());
2367
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002368 // Check that the system user remains affiliated.
2369 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2370 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002371
2372 // Clear the device owner - the user becomes unaffiliated.
2373 clearDeviceOwner();
2374 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002375 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002376
2377 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002378 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002379 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2380 }
2381
2382 public void testSetUserProvisioningState_permission() throws Exception {
2383 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002384
2385 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2386 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2387 }
2388
2389 public void testSetUserProvisioningState_unprivileged() throws Exception {
2390 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002391 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2392 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2393 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002394 }
2395
2396 public void testSetUserProvisioningState_noManagement() {
2397 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002398 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002399 assertExpectException(IllegalStateException.class,
2400 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2401 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2402 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002403 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2404 }
2405
2406 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2407 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2408 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002409
2410 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2411 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2412 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2413 }
2414
2415 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2416 throws Exception {
2417 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2418 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002419
2420 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2421 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2422 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2423 }
2424
2425 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2426 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2427 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002428
2429 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2430 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2431 }
2432
2433 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2434 throws Exception {
2435 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002436
2437 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2438 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2439 DevicePolicyManager.STATE_USER_UNMANAGED);
2440 }
2441
2442 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2443 throws Exception {
2444 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002445
2446 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2447 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2448 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2449 }
2450
2451 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2452 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002453
2454 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2455 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2456 }
2457
2458 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2459 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002460
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002461 assertExpectException(IllegalStateException.class,
2462 /* messageRegex= */ "Cannot move to user provisioning state",
2463 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2464 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2465 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002466 }
2467
2468 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2469 throws Exception {
2470 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002471
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002472 assertExpectException(IllegalStateException.class,
2473 /* messageRegex= */ "Cannot move to user provisioning state",
2474 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2475 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2476 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002477 }
2478
2479 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002480 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2481 mContext.callerPermissions.add(permission.MANAGE_USERS);
2482
Alan Treadwayafad8782016-01-19 15:15:08 +00002483 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2484 for (int state : states) {
2485 dpm.setUserProvisioningState(state, userId);
2486 assertEquals(state, dpm.getUserProvisioningState());
2487 }
2488 }
2489
2490 private void setupProfileOwner() throws Exception {
2491 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2492
2493 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2494 dpm.setActiveAdmin(admin1, false);
2495 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2496
2497 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2498 }
2499
2500 private void setupDeviceOwner() throws Exception {
2501 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2502
2503 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2504 dpm.setActiveAdmin(admin1, false);
2505 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2506
2507 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2508 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002509
2510 public void testSetMaximumTimeToLock() {
2511 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2512
2513 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2514 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2515
Pavel Grafov75c0a892017-05-18 17:28:27 +01002516 reset(getServices().powerManagerInternal);
2517 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002518
2519 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002520 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2521 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002522 reset(getServices().powerManagerInternal);
2523 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002524
2525 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002526 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2527 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002528 reset(getServices().powerManagerInternal);
2529 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002530
2531 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002532 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2533 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002534 reset(getServices().powerManagerInternal);
2535 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002536
2537 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002538 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2539 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002540 reset(getServices().powerManagerInternal);
2541 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002542
2543 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002544 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2545 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002546 reset(getServices().powerManagerInternal);
2547 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002548
2549 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002550 reset(getServices().powerManagerInternal);
2551 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002552
Pavel Grafov28939982017-10-03 15:11:52 +01002553 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2554 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2555 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002556 reset(getServices().powerManagerInternal);
2557 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002558
2559 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002560 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2561 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002562 reset(getServices().powerManagerInternal);
2563 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002564
Pavel Grafov28939982017-10-03 15:11:52 +01002565 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002566 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002567 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2568 verifyStayOnWhilePluggedCleared(false);
2569 }
2570
2571 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2572 // uses separate challenge.
2573 public void testSetMaximumTimeToLockProfile() throws Exception {
2574 final int PROFILE_USER = 15;
2575 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2576 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2577 mContext.binder.callingUid = PROFILE_ADMIN;
2578 final DevicePolicyManagerInternal dpmi =
2579 LocalServices.getService(DevicePolicyManagerInternal.class);
2580
2581 dpm.setMaximumTimeToLock(admin1, 0);
2582
2583 reset(getServices().powerManagerInternal);
2584 reset(getServices().settings);
2585
2586 // First add timeout for the profile.
2587 dpm.setMaximumTimeToLock(admin1, 10);
2588 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2589
2590 reset(getServices().powerManagerInternal);
2591 reset(getServices().settings);
2592
2593 // Add separate challenge
2594 when(getServices().lockPatternUtils
2595 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2596 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2597
2598 verifyScreenTimeoutCall(10L, PROFILE_USER);
2599 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2600
2601 reset(getServices().powerManagerInternal);
2602 reset(getServices().settings);
2603
2604 // Remove the timeout.
2605 dpm.setMaximumTimeToLock(admin1, 0);
2606 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2607 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2608
2609 reset(getServices().powerManagerInternal);
2610 reset(getServices().settings);
2611
2612 // Add it back.
2613 dpm.setMaximumTimeToLock(admin1, 10);
2614 verifyScreenTimeoutCall(10L, PROFILE_USER);
2615 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2616
2617 reset(getServices().powerManagerInternal);
2618 reset(getServices().settings);
2619
2620 // Remove separate challenge.
2621 reset(getServices().lockPatternUtils);
2622 when(getServices().lockPatternUtils
2623 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2624 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002625 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002626
2627 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2628 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2629
2630 reset(getServices().powerManagerInternal);
2631 reset(getServices().settings);
2632
2633 // Remove the timeout.
2634 dpm.setMaximumTimeToLock(admin1, 0);
2635 verifyScreenTimeoutCall(null, PROFILE_USER);
2636 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002637 }
2638
Michal Karpinski943aabd2016-10-06 11:09:25 +01002639 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2640 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2641 setupDeviceOwner();
2642 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2643
Michal Karpinskid084ca52017-01-18 15:54:18 +00002644 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2645 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2646 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2647 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2648 - ONE_MINUTE;
2649
2650 // verify that the minimum timeout cannot be modified on user builds (system property is
2651 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002652 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002653
2654 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2655 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2656 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2657
Pavel Grafov75c0a892017-05-18 17:28:27 +01002658 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002659
2660 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002661 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002662
Michal Karpinskid084ca52017-01-18 15:54:18 +00002663 // reset to default (0 means the admin is not participating, so default should be returned)
2664 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002665
2666 // aggregation should be the default if unset by any admin
2667 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2668 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2669
2670 // admin not participating by default
2671 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2672
2673 //clamping from the top
2674 dpm.setRequiredStrongAuthTimeout(admin1,
2675 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2676 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2677 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2678 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2679 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2680
Michal Karpinskid084ca52017-01-18 15:54:18 +00002681 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002682 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2683 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2684 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2685 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2686
2687 // clamping from the bottom
2688 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2691
Michal Karpinskid084ca52017-01-18 15:54:18 +00002692 // values within range
2693 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2696
2697 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2699 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002700
2701 // reset to default
2702 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2703 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2704 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2705 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2706
2707 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002708 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2709 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002710 }
2711
Pavel Grafov28939982017-10-03 15:11:52 +01002712 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002713 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002714 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002715 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002716 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002717 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002718 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002719 }
Pavel Grafov28939982017-10-03 15:11:52 +01002720 }
2721
2722 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002723 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2724 // UnfinishedVerificationException.
2725 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002726
Esteban Talavera01576862016-12-15 11:16:44 +00002727 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002729 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002730 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002731 .thenReturn(false);
2732 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002733 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2734 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002735 .thenReturn(true);
2736 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2737
2738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002739 }
Victor Chang3e794af2016-03-04 13:48:17 +00002740
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002741 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2742 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002743 mContext.packageName = admin1.getPackageName();
2744 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2746 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2747 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2748 false);
2749 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2750 }
2751
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002752 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2753 setup_DeviceAdminFeatureOff();
2754 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2755 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2756 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2757 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2758 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2759 assertCheckProvisioningPreCondition(
2760 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2761 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2762 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2763 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2764 }
2765
Esteban Talavera01576862016-12-15 11:16:44 +00002766 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002767 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002768 .thenReturn(false);
2769 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002770 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2771 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002772 .thenReturn(true);
2773 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2774
2775 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002776 }
Victor Chang3e794af2016-03-04 13:48:17 +00002777
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002778 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2779 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002780 mContext.packageName = admin1.getPackageName();
2781 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2783 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2784 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2785 false);
2786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2787
2788 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002789 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2791 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2792 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2793 true);
2794 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2795 }
2796
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002797 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2798 setup_ManagedProfileFeatureOff();
2799 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2800 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2801 DevicePolicyManager.CODE_OK);
2802 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2803 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2804 assertCheckProvisioningPreCondition(
2805 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2806 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2807 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2808 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2809
2810 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002811 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002812 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2813 DevicePolicyManager.CODE_OK);
2814 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2815 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2816 assertCheckProvisioningPreCondition(
2817 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2818 DevicePolicyManager.CODE_OK);
2819 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2820 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2821 }
2822
Esteban Talavera01576862016-12-15 11:16:44 +00002823 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002824 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002825 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002826 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2827 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002828 .thenReturn(true);
2829 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2830
2831 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002832 }
Victor Chang3e794af2016-03-04 13:48:17 +00002833
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2835 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002836 mContext.packageName = admin1.getPackageName();
2837 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2839 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2840 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2841 false /* because of non-split user */);
2842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2843 false /* because of non-split user */);
2844 }
2845
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002846 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002847 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002848 setup_nonSplitUser_firstBoot_primaryUser();
2849 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2850 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2851 DevicePolicyManager.CODE_OK);
2852 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2853 DevicePolicyManager.CODE_OK);
2854 assertCheckProvisioningPreCondition(
2855 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2856 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2857 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2858 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2859 }
2860
Esteban Talavera01576862016-12-15 11:16:44 +00002861 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002862 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002863 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002864 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2865 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002866 .thenReturn(true);
2867 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2868
2869 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 }
Victor Chang3e794af2016-03-04 13:48:17 +00002871
Nicolas Prevot45d29072017-01-18 16:11:19 +00002872 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2873 setDeviceOwner();
2874 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2875 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2876 }
2877
2878 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2879 setup_nonSplitUser_withDo_primaryUser();
2880 final int MANAGED_PROFILE_USER_ID = 18;
2881 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2882 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002883 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002884 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002885 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002886 true)).thenReturn(true);
2887 }
2888
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002889 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2890 throws Exception {
2891 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002892 mContext.packageName = admin1.getPackageName();
2893 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002894 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2895 false/* because of completed device setup */);
2896 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2897 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2898 false/* because of non-split user */);
2899 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2900 false/* because of non-split user */);
2901 }
2902
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002903 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2904 throws Exception {
2905 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2906 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2907 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2908 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2909 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2910 DevicePolicyManager.CODE_OK);
2911 assertCheckProvisioningPreCondition(
2912 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2913 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2914 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2915 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2916 }
2917
Nicolas Prevot45d29072017-01-18 16:11:19 +00002918 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2919 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002920 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002921 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2922
2923 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2924 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002925 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002926
2927 // COMP mode is allowed.
2928 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2929 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002930 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002931
Nicolas Prevot45d29072017-01-18 16:11:19 +00002932 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002933 assertCheckProvisioningPreCondition(
2934 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002935 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002936 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2938 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2939 }
Esteban Talavera01576862016-12-15 11:16:44 +00002940
Nicolas Prevot45d29072017-01-18 16:11:19 +00002941 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2942 setup_nonSplitUser_withDo_primaryUser();
2943 mContext.packageName = admin1.getPackageName();
2944 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2945 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2946 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002947 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002948 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2949 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2950 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002951 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002952 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2953 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2954 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2955 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2956 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002958 assertCheckProvisioningPreCondition(
2959 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002960 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002961 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002962 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2963 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2964 }
Esteban Talavera01576862016-12-15 11:16:44 +00002965
Nicolas Prevot45d29072017-01-18 16:11:19 +00002966 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2967 throws Exception {
2968 setup_nonSplitUser_withDo_primaryUser();
2969 mContext.packageName = admin1.getPackageName();
2970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002971 // The DO should not be allowed to initiate provisioning if the restriction is set by
2972 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002973 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002974 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2975 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2976 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002977 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002978 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2979 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2980 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2981 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2982 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002983 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2984
2985 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002986 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002987 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002988 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002989 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2990 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2991 }
2992
2993 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2994 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2995 mContext.packageName = admin1.getPackageName();
2996 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2997
2998 // We can delete the managed profile to create a new one, so provisioning is allowed.
2999 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3000 DevicePolicyManager.CODE_OK);
3001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3002 assertCheckProvisioningPreCondition(
3003 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3004 DpmMockContext.ANOTHER_PACKAGE_NAME,
3005 DevicePolicyManager.CODE_OK);
3006 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3007 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3008 }
3009
3010 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3011 throws Exception {
3012 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3013 mContext.packageName = admin1.getPackageName();
3014 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003015 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003016 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3017 eq(UserHandle.SYSTEM)))
3018 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003019 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003020 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3021 eq(UserHandle.SYSTEM)))
3022 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003023
3024 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003025 assertCheckProvisioningPreCondition(
3026 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3027 DpmMockContext.ANOTHER_PACKAGE_NAME,
3028 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3029 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3030 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003031
3032 // But the device owner can still do it because it has set the restriction itself.
3033 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3034 DevicePolicyManager.CODE_OK);
3035 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003036 }
3037
3038 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003039 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003040 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003041 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3042 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003043 .thenReturn(false);
3044 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3045
3046 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003047 }
Victor Chang3e794af2016-03-04 13:48:17 +00003048
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003049 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3050 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003051 mContext.packageName = admin1.getPackageName();
3052 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003053 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3055 false /* because canAddMoreManagedProfiles returns false */);
3056 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3057 true);
3058 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3059 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003060 }
3061
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003062 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3063 throws Exception {
3064 setup_splitUser_firstBoot_systemUser();
3065 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3066 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3067 DevicePolicyManager.CODE_OK);
3068 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003069 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003070 assertCheckProvisioningPreCondition(
3071 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3072 DevicePolicyManager.CODE_OK);
3073 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3074 DevicePolicyManager.CODE_SYSTEM_USER);
3075 }
3076
Esteban Talavera01576862016-12-15 11:16:44 +00003077 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003078 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003079 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003080 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3081 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003082 .thenReturn(false);
3083 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3084
3085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003086 }
Victor Chang3e794af2016-03-04 13:48:17 +00003087
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003088 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3089 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003090 mContext.packageName = admin1.getPackageName();
3091 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003092 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3093 true/* it's undefined behavior. Can be changed into false in the future */);
3094 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3095 false /* because canAddMoreManagedProfiles returns false */);
3096 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3097 true/* it's undefined behavior. Can be changed into false in the future */);
3098 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3099 false/* because calling uid is system user */);
3100 }
3101
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003102 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3103 throws Exception {
3104 setup_splitUser_afterDeviceSetup_systemUser();
3105 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3106 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3107 DevicePolicyManager.CODE_OK);
3108 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003109 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003110 assertCheckProvisioningPreCondition(
3111 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3112 DevicePolicyManager.CODE_OK);
3113 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3114 DevicePolicyManager.CODE_SYSTEM_USER);
3115 }
3116
Esteban Talavera01576862016-12-15 11:16:44 +00003117 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003118 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003119 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003120 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3121 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003122 true)).thenReturn(true);
3123 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3124
3125 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003126 }
Victor Chang3e794af2016-03-04 13:48:17 +00003127
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003128 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3129 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003130 mContext.packageName = admin1.getPackageName();
3131 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3134 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3135 true);
3136 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003137 }
3138
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003139 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003140 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003141 setup_splitUser_firstBoot_primaryUser();
3142 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3143 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3144 DevicePolicyManager.CODE_OK);
3145 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3146 DevicePolicyManager.CODE_OK);
3147 assertCheckProvisioningPreCondition(
3148 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3149 DevicePolicyManager.CODE_OK);
3150 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3151 DevicePolicyManager.CODE_OK);
3152 }
3153
Esteban Talavera01576862016-12-15 11:16:44 +00003154 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003155 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003156 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003157 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3158 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003159 true)).thenReturn(true);
3160 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3161
3162 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003163 }
Victor Chang3e794af2016-03-04 13:48:17 +00003164
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003165 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3166 throws Exception {
3167 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003168 mContext.packageName = admin1.getPackageName();
3169 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003170 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3171 true/* it's undefined behavior. Can be changed into false in the future */);
3172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3173 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3174 true/* it's undefined behavior. Can be changed into false in the future */);
3175 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3176 false/* because user setup completed */);
3177 }
3178
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003179 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003180 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003181 setup_splitUser_afterDeviceSetup_primaryUser();
3182 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3183 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3184 DevicePolicyManager.CODE_OK);
3185 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3186 DevicePolicyManager.CODE_OK);
3187 assertCheckProvisioningPreCondition(
3188 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3189 DevicePolicyManager.CODE_OK);
3190 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3191 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3192 }
3193
Esteban Talavera01576862016-12-15 11:16:44 +00003194 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003195 setDeviceOwner();
3196
Pavel Grafov75c0a892017-05-18 17:28:27 +01003197 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003198 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003199 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3200 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003201 .thenReturn(false);
3202 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3203
3204 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003205 }
Victor Chang3e794af2016-03-04 13:48:17 +00003206
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003207 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3208 throws Exception {
3209 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003210 mContext.packageName = admin1.getPackageName();
3211 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003212 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3213 false /* can't provision managed profile on system user */);
3214 }
3215
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003216 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003217 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003218 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3219 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3220 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3221 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3222 }
3223
3224 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003225 setDeviceOwner();
3226
Pavel Grafov75c0a892017-05-18 17:28:27 +01003227 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003228 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003229 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3230 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003231 true)).thenReturn(true);
3232 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3233
3234 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003235 }
Victor Chang3e794af2016-03-04 13:48:17 +00003236
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003237 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3238 throws Exception {
3239 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003240 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3241 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003242 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3243 }
3244
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003245 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003246 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003247 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3248 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003249
3250 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003251 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3252 DevicePolicyManager.CODE_OK);
3253 }
3254
3255 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003256 setDeviceOwner();
3257
Pavel Grafov75c0a892017-05-18 17:28:27 +01003258 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003259 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003260 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3261 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003262 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3263 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003264 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003265 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003266 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003267 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003268 true)).thenReturn(true);
3269 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3270
3271 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003272 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003273
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003274 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3275 throws Exception {
3276 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003277 mContext.packageName = admin1.getPackageName();
3278 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003279 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3280 }
3281
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003282 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3283 throws Exception {
3284 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3285 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3286 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3287 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3288 }
3289
3290 public void testCheckProvisioningPreCondition_permission() {
3291 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003292 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3293 () -> dpm.checkProvisioningPreCondition(
3294 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003295 }
3296
Victor Chang3577ed22016-08-25 18:49:26 +01003297 public void testForceUpdateUserSetupComplete_permission() {
3298 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003299 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3300 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003301 }
3302
3303 public void testForceUpdateUserSetupComplete_systemUser() {
3304 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3305 // GIVEN calling from user 20
3306 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003307 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3308 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003309 }
3310
3311 public void testForceUpdateUserSetupComplete_userbuild() {
3312 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3313 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3314
3315 final int userId = UserHandle.USER_SYSTEM;
3316 // GIVEN userComplete is false in SettingsProvider
3317 setUserSetupCompleteForUser(false, userId);
3318
3319 // GIVEN userComplete is true in DPM
3320 DevicePolicyManagerService.DevicePolicyData userData =
3321 new DevicePolicyManagerService.DevicePolicyData(userId);
3322 userData.mUserSetupComplete = true;
3323 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3324
3325 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003326 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003327
3328 assertTrue(dpms.hasUserSetupCompleted());
3329
3330 dpm.forceUpdateUserSetupComplete();
3331
3332 // THEN the state in dpms is not changed
3333 assertTrue(dpms.hasUserSetupCompleted());
3334 }
3335
3336 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3337 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3339
3340 final int userId = UserHandle.USER_SYSTEM;
3341 // GIVEN userComplete is false in SettingsProvider
3342 setUserSetupCompleteForUser(false, userId);
3343
3344 // GIVEN userComplete is true in DPM
3345 DevicePolicyManagerService.DevicePolicyData userData =
3346 new DevicePolicyManagerService.DevicePolicyData(userId);
3347 userData.mUserSetupComplete = true;
3348 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3349
3350 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003351 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003352
3353 assertTrue(dpms.hasUserSetupCompleted());
3354
3355 dpm.forceUpdateUserSetupComplete();
3356
3357 // THEN the state in dpms is not changed
3358 assertFalse(dpms.hasUserSetupCompleted());
3359 }
3360
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003361 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003362 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003363 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003364
3365 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3366 runAsCaller(mAdmin1Context, dpms, dpm -> {
3367 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3368 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003369 }
3370
3371 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3372 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3373 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003374
3375 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3376 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003377 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003378 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3379 .thenReturn(true);
3380
3381 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003382 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003383
3384 // Enabling logging should not change the timestamp.
3385 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003386 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003387 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003388 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003389 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003390 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003391
3392 // Retrieving the logs should update the timestamp.
3393 final long beforeRetrieval = System.currentTimeMillis();
3394 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003395 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003396 final long afterRetrieval = System.currentTimeMillis();
3397 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3398 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3399
3400 // Retrieving the pre-boot logs should update the timestamp.
3401 Thread.sleep(2);
3402 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003403 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003404 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3405
3406 // Checking the timestamp again should not change it.
3407 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003408 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003409
3410 // Retrieving the logs again should update the timestamp.
3411 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003412 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003413 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3414
3415 // Disabling logging should not change the timestamp.
3416 Thread.sleep(2);
3417 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003418 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003419
3420 // Restarting the DPMS should not lose the timestamp.
3421 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003422 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003423
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003424 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3425 mContext.binder.callingUid = 1234567;
3426 mContext.callerPermissions.add(permission.MANAGE_USERS);
3427 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3428 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3429
3430 // System can retrieve the timestamp.
3431 mContext.binder.clearCallingIdentity();
3432 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3433
3434 // Removing the device owner should clear the timestamp.
3435 clearDeviceOwner();
3436 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003437 }
3438
yuemingw0de748d2017-11-15 19:22:27 +00003439 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441 setupDeviceOwner();
3442 assertExpectException(SecurityException.class, null, () ->
3443 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3444 }
3445
yuemingwc0281f12018-03-28 15:58:49 +01003446 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003447 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3448 setupDeviceOwner();
3449 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003450 verify(getServices().settings).settingsSystemPutStringForUser(
3451 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3452 }
3453
3454 public void testSetSystemSettingWithPO() throws Exception {
3455 setupProfileOwner();
3456 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3457 verify(getServices().settings).settingsSystemPutStringForUser(
3458 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003459 }
3460
yuemingwe43cdf72017-10-12 16:52:11 +01003461 public void testSetTime() throws Exception {
3462 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3463 setupDeviceOwner();
3464 dpm.setTime(admin1, 0);
3465 verify(getServices().alarmManager).setTime(0);
3466 }
3467
3468 public void testSetTimeFailWithPO() throws Exception {
3469 setupProfileOwner();
3470 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3471 }
3472
3473 public void testSetTimeWithAutoTimeOn() throws Exception {
3474 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3475 setupDeviceOwner();
3476 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3477 .thenReturn(1);
3478 assertFalse(dpm.setTime(admin1, 0));
3479 }
3480
3481 public void testSetTimeZone() throws Exception {
3482 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3483 setupDeviceOwner();
3484 dpm.setTimeZone(admin1, "Asia/Shanghai");
3485 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3486 }
3487
3488 public void testSetTimeZoneFailWithPO() throws Exception {
3489 setupProfileOwner();
3490 assertExpectException(SecurityException.class, null,
3491 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3492 }
3493
3494 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3495 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3496 setupDeviceOwner();
3497 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3498 .thenReturn(1);
3499 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3500 }
3501
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003502 public void testGetLastBugReportRequestTime() throws Exception {
3503 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3504 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003505
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003506 mContext.packageName = admin1.getPackageName();
3507 mContext.applicationInfo = new ApplicationInfo();
3508 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3509 .thenReturn(Color.WHITE);
3510 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3511 anyObject())).thenReturn(Color.WHITE);
3512
Esteban Talaverad36dd152016-12-15 08:51:45 +00003513 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3514 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003515 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003516
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003518 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003519
3520 // Requesting a bug report should update the timestamp.
3521 final long beforeRequest = System.currentTimeMillis();
3522 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003523 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003524 final long afterRequest = System.currentTimeMillis();
3525 assertTrue(bugReportRequestTime >= beforeRequest);
3526 assertTrue(bugReportRequestTime <= afterRequest);
3527
3528 // Checking the timestamp again should not change it.
3529 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003530 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003531
3532 // Restarting the DPMS should not lose the timestamp.
3533 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003534 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003535
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003536 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3537 mContext.binder.callingUid = 1234567;
3538 mContext.callerPermissions.add(permission.MANAGE_USERS);
3539 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3540 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3541
3542 // System can retrieve the timestamp.
3543 mContext.binder.clearCallingIdentity();
3544 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3545
3546 // Removing the device owner should clear the timestamp.
3547 clearDeviceOwner();
3548 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003549 }
3550
3551 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3552 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3553 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003554 mContext.packageName = admin1.getPackageName();
3555 mContext.applicationInfo = new ApplicationInfo();
3556 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3557 .thenReturn(Color.WHITE);
3558 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3559 anyObject())).thenReturn(Color.WHITE);
3560
3561 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3562 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003563 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003564 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003565 .thenReturn(true);
3566
3567 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003568 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003569
3570 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3571 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003572 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003573
3574 // Enabling logging should not change the timestamp.
3575 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003576 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003577
3578 // Retrieving the logs should update the timestamp.
3579 final long beforeRetrieval = System.currentTimeMillis();
3580 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003581 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003582 final long afterRetrieval = System.currentTimeMillis();
3583 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3584 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3585
3586 // Checking the timestamp again should not change it.
3587 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003588 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003589
3590 // Retrieving the logs again should update the timestamp.
3591 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003592 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003593 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3594
3595 // Disabling logging should not change the timestamp.
3596 Thread.sleep(2);
3597 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003598 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003599
3600 // Restarting the DPMS should not lose the timestamp.
3601 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003602 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3603
3604 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3605 mContext.binder.callingUid = 1234567;
3606 mContext.callerPermissions.add(permission.MANAGE_USERS);
3607 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3608 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3609
3610 // System can retrieve the timestamp.
3611 mContext.binder.clearCallingIdentity();
3612 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3613
3614 // Removing the device owner should clear the timestamp.
3615 clearDeviceOwner();
3616 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003617 }
3618
Tony Mak2f26b792016-11-28 17:54:51 +00003619 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3620 // Setup device owner.
3621 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3622 setupDeviceOwner();
3623
3624 // Only device owner is setup, the result list should be empty.
3625 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3626 MoreAsserts.assertEmpty(targetUsers);
3627
3628 // Setup a managed profile managed by the same admin.
3629 final int MANAGED_PROFILE_USER_ID = 15;
3630 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3631 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3632
3633 // Add a secondary user, it should never talk with.
3634 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003635 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003636
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003637 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3638 // other.
3639 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3640 MoreAsserts.assertEmpty(targetUsers);
3641
3642 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3643 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3644 MoreAsserts.assertEmpty(targetUsers);
3645
3646 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003647 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003648 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3649 dpm.setAffiliationIds(admin1, userAffiliationIds);
3650
3651 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3652 dpm.setAffiliationIds(admin1, userAffiliationIds);
3653
Tony Mak2f26b792016-11-28 17:54:51 +00003654 // Calling from device owner admin, the result list should just contain the managed
3655 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003656 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003657 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3658 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3659
3660 // Calling from managed profile admin, the result list should just contain the system
3661 // user id.
3662 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3663 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3664 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003665
3666 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003667 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003668
3669 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3670 // to each other.
3671 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3672 MoreAsserts.assertEmpty(targetUsers);
3673
3674 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3675 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3676 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003677 }
3678
3679 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3680 // Setup a device owner.
3681 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3682 setupDeviceOwner();
3683
3684 // Set up a managed profile managed by different package.
3685 final int MANAGED_PROFILE_USER_ID = 15;
3686 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3687 final ComponentName adminDifferentPackage =
3688 new ComponentName("another.package", "whatever.class");
3689 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3690
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003691 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003692 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003693 dpm.setAffiliationIds(admin1, userAffiliationIds);
3694
3695 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3696 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3697
Tony Mak2f26b792016-11-28 17:54:51 +00003698 // Calling from device owner admin, we should get zero bind device admin target users as
3699 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003701 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3702 MoreAsserts.assertEmpty(targetUsers);
3703
3704 // Calling from managed profile admin, we should still get zero target users for the same
3705 // reason.
3706 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3707 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3708 MoreAsserts.assertEmpty(targetUsers);
3709 }
3710
Jason Parks3c13b642017-11-28 15:39:43 -06003711 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003712 verifyLockTaskState(userId, new String[0],
3713 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003714 }
3715
3716 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3717 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003718 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003719 }
3720
3721 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3722 int flags) throws Exception {
3723 mContext.binder.callingUid = uid;
3724 dpm.setLockTaskPackages(who, packages);
3725 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3726 for (String p : packages) {
3727 assertTrue(dpm.isLockTaskPermitted(p));
3728 }
3729 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3730 // Test to see if set lock task features can be set
3731 dpm.setLockTaskFeatures(who, flags);
3732 verifyLockTaskState(userId, packages, flags);
3733 }
3734
3735 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3736 int flags) throws Exception {
3737 mContext.binder.callingUid = uid;
3738 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3739 () -> dpm.setLockTaskPackages(who, packages));
3740 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3741 () -> dpm.getLockTaskPackages(who));
3742 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3743 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3744 () -> dpm.setLockTaskFeatures(who, flags));
3745 }
3746
Charles Hee078db72017-10-19 18:03:20 +01003747 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003748 // Setup a device owner.
3749 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3750 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003751 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003752 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003753
3754 // Set up a managed profile managed by different package (package name shouldn't matter)
3755 final int MANAGED_PROFILE_USER_ID = 15;
3756 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3757 final ComponentName adminDifferentPackage =
3758 new ComponentName("another.package", "whatever.class");
3759 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003760 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3761
3762 // Setup a PO on the secondary user
3763 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3764 setAsProfileOwner(admin3);
3765 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003766
3767 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003768 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003769 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003770 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3771 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003772 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3773
3774 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3775 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003776 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3777 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003778 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003779
3780 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3781 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3782 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003783 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003784 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3785 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003786 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003787
3788 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003789 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003790 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3791 dpm.setAffiliationIds(admin1, userAffiliationIds);
3792
3793 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3794 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3795
3796 // Now the managed profile can set lock task packages.
3797 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3798 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3799 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3800 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003801 // And it can set lock task features.
3802 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003803 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003804
3805 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003806 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003807 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3808 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003809 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3810 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003811 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003812 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003813
Jason Parks3c13b642017-11-28 15:39:43 -06003814 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003815 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3816 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003817
3818 }
3819
3820 public void testLockTaskPolicyForProfileOwner() throws Exception {
3821 // Setup a PO
3822 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3823 setAsProfileOwner(admin1);
3824 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3825
3826 final String[] poPackages = {"poPackage1", "poPackage2"};
3827 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003828 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3829 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003830 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3831 poPackages, poFlags);
3832
3833 // Set up a managed profile managed by different package (package name shouldn't matter)
3834 final int MANAGED_PROFILE_USER_ID = 15;
3835 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3836 final ComponentName adminDifferentPackage =
3837 new ComponentName("another.package", "whatever.class");
3838 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3839 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3840
3841 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3842 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3843 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3844 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003845 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3846 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003847 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003848 }
3849
Benjamin Franzcaffa772018-02-05 16:36:10 +00003850 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3851 // Setup a device owner.
3852 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3853 setupDeviceOwner();
3854 // Lock task policy is updated when loading user data.
3855 verifyLockTaskState(UserHandle.USER_SYSTEM);
3856
3857 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3858 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3859 assertExpectException(IllegalArgumentException.class,
3860 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3861 () -> dpm.setLockTaskFeatures(admin1, flags));
3862 }
3863
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003864 public void testIsDeviceManaged() throws Exception {
3865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3866 setupDeviceOwner();
3867
3868 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3869 // find out that the device has a device owner.
3870 assertTrue(dpm.isDeviceManaged());
3871 mContext.binder.callingUid = 1234567;
3872 mContext.callerPermissions.add(permission.MANAGE_USERS);
3873 assertTrue(dpm.isDeviceManaged());
3874 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3875 mContext.binder.clearCallingIdentity();
3876 assertTrue(dpm.isDeviceManaged());
3877
3878 clearDeviceOwner();
3879
3880 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3881 // not have a device owner.
3882 mContext.binder.callingUid = 1234567;
3883 mContext.callerPermissions.add(permission.MANAGE_USERS);
3884 assertFalse(dpm.isDeviceManaged());
3885 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3886 mContext.binder.clearCallingIdentity();
3887 assertFalse(dpm.isDeviceManaged());
3888 }
3889
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003890 public void testDeviceOwnerOrganizationName() throws Exception {
3891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3892 setupDeviceOwner();
3893
3894 dpm.setOrganizationName(admin1, "organization");
3895
3896 // Device owner can retrieve organization managing the device.
3897 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3898
3899 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3900 mContext.binder.callingUid = 1234567;
3901 mContext.callerPermissions.add(permission.MANAGE_USERS);
3902 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3903 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3904
3905 // System can retrieve organization managing the device.
3906 mContext.binder.clearCallingIdentity();
3907 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3908
3909 // Removing the device owner clears the organization managing the device.
3910 clearDeviceOwner();
3911 assertNull(dpm.getDeviceOwnerOrganizationName());
3912 }
3913
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003914 public void testWipeDataManagedProfile() throws Exception {
3915 final int MANAGED_PROFILE_USER_ID = 15;
3916 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3917 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3918 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3919
3920 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003921 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003922 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003923 // Get mock reason string since we throw an IAE with empty string input.
3924 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3925 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003926
3927 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003928 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003929 MANAGED_PROFILE_USER_ID);
3930 }
3931
3932 public void testWipeDataManagedProfileDisallowed() throws Exception {
3933 final int MANAGED_PROFILE_USER_ID = 15;
3934 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3935 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3936
3937 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003938 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003939 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3940
Pavel Grafov75c0a892017-05-18 17:28:27 +01003941 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003942 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3943 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3944 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003945 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3946 thenReturn("Just a test string.");
3947
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003948 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003949 // The PO is not allowed to remove the profile if the user restriction was set on the
3950 // profile by the system
3951 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3952 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003953 }
3954
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003955 public void testWipeDataDeviceOwner() throws Exception {
3956 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003957 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003958 UserManager.DISALLOW_FACTORY_RESET,
3959 UserHandle.SYSTEM))
3960 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003961 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3962 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003963
3964 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003965 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003966 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3967 /*wipeEuicc=*/ eq(false));
3968 }
3969
3970 public void testWipeEuiccDataEnabled() throws Exception {
3971 setDeviceOwner();
3972 when(getServices().userManager.getUserRestrictionSource(
3973 UserManager.DISALLOW_FACTORY_RESET,
3974 UserHandle.SYSTEM))
3975 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003976 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3977 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003978
3979 dpm.wipeData(WIPE_EUICC);
3980 verify(getServices().recoverySystem).rebootWipeUserData(
3981 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3982 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003983 }
3984
3985 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3986 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003987 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003988 UserManager.DISALLOW_FACTORY_RESET,
3989 UserHandle.SYSTEM))
3990 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003991 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3992 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003993 // The DO is not allowed to wipe the device if the user restriction was set
3994 // by the system
3995 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3996 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003997 }
3998
3999 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4000 final int MANAGED_PROFILE_USER_ID = 15;
4001 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4002 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4003
4004 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004005 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004006 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4007
Pavel Grafov75c0a892017-05-18 17:28:27 +01004008 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004009 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4010 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4011 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4012
4013 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4014 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4015
4016 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4017 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4018 // Failed password attempts on the parent user are taken into account, as there isn't a
4019 // separate work challenge.
4020 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4021 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4022 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4023
4024 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4025 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004026 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004027 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004028 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004029 }
4030
4031 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4032 throws Exception {
4033 final int MANAGED_PROFILE_USER_ID = 15;
4034 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4035 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4036
4037 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004039 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4040
Pavel Grafov75c0a892017-05-18 17:28:27 +01004041 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004042 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4043 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4044 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4045
4046 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4047 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4048
4049 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4050 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4051 // Failed password attempts on the parent user are taken into account, as there isn't a
4052 // separate work challenge.
4053 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4054 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4055 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4056
4057 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4058 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004059 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004060 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004061 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004062 }
4063
4064 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4065 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004066 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004067 UserManager.DISALLOW_FACTORY_RESET,
4068 UserHandle.SYSTEM))
4069 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4070
4071 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4072
4073 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4074 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4075 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4076 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4077 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4078
4079 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4080 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004082 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4083 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004084 }
4085
4086 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4087 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004088 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004089 UserManager.DISALLOW_FACTORY_RESET,
4090 UserHandle.SYSTEM))
4091 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4092
4093 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4094
4095 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4096 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4097 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4098 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4099 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4100
4101 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004102 verifyZeroInteractions(getServices().recoverySystem);
4103 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004104 .removeUserEvenWhenDisallowed(anyInt());
4105 }
4106
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004107 public void testGetPermissionGrantState() throws Exception {
4108 final String permission = "some.permission";
4109 final String app1 = "com.example.app1";
4110 final String app2 = "com.example.app2";
4111
Pavel Grafov75c0a892017-05-18 17:28:27 +01004112 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004113 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004115 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004116 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004117 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4118 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004119 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004120 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004121 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004122 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004124 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4125
4126 // System can retrieve permission grant state.
4127 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004128 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004129 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4130 dpm.getPermissionGrantState(null, app1, permission));
4131 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4132 dpm.getPermissionGrantState(null, app2, permission));
4133
4134 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004135 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4136 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004137 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4138 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004139
4140 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004141 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4142 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004143 setAsProfileOwner(admin1);
4144 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4145 dpm.getPermissionGrantState(admin1, app1, permission));
4146 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4147 dpm.getPermissionGrantState(admin1, app2, permission));
4148 }
4149
Rubin Xuaab7a412016-12-30 21:13:29 +00004150 public void testResetPasswordWithToken() throws Exception {
4151 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4152 setupDeviceOwner();
4153 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004154 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4155 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4156
Rubin Xuaab7a412016-12-30 21:13:29 +00004157 // test adding a token
4158 final byte[] token = new byte[32];
4159 final long handle = 123456;
4160 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004161 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4162 nullable(EscrowTokenStateChangeCallback.class)))
4163 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004164 assertTrue(dpm.setResetPasswordToken(admin1, token));
4165
4166 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004167 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004168 .thenReturn(true);
4169 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4170
4171 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004172 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004173 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004174 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004175 eq(UserHandle.USER_SYSTEM)))
4176 .thenReturn(true);
4177 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4178
4179 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004180 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004181 .thenReturn(true);
4182 assertTrue(dpm.clearResetPasswordToken(admin1));
4183 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004184
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004185 public void testIsActivePasswordSufficient() throws Exception {
4186 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4187 mContext.packageName = admin1.getPackageName();
4188 setupDeviceOwner();
4189
4190 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4191 dpm.setPasswordMinimumLength(admin1, 8);
4192 dpm.setPasswordMinimumLetters(admin1, 6);
4193 dpm.setPasswordMinimumLowerCase(admin1, 3);
4194 dpm.setPasswordMinimumUpperCase(admin1, 1);
4195 dpm.setPasswordMinimumNonLetter(admin1, 1);
4196 dpm.setPasswordMinimumNumeric(admin1, 1);
4197 dpm.setPasswordMinimumSymbols(admin1, 0);
4198
Rubin Xucc391c22018-01-02 20:37:35 +00004199 reset(mContext.spiedContext);
4200
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004201 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4202 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4203 8, 2,
4204 6, 1,
4205 0, 1);
4206
4207 setActivePasswordState(passwordMetricsNoSymbols);
4208 assertTrue(dpm.isActivePasswordSufficient());
4209
4210 initializeDpms();
4211 reset(mContext.spiedContext);
4212 assertTrue(dpm.isActivePasswordSufficient());
4213
4214 // This call simulates the user entering the password for the first time after a reboot.
4215 // This causes password metrics to be reloaded into memory. Until this happens,
4216 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4217 // even if the DPC changes password requirements so that the password no longer meets the
4218 // requirements. This is a known limitation of the current implementation of
4219 // isActivePasswordSufficient() - see b/34218769.
4220 setActivePasswordState(passwordMetricsNoSymbols);
4221 assertTrue(dpm.isActivePasswordSufficient());
4222
4223 dpm.setPasswordMinimumSymbols(admin1, 1);
4224 // This assertion would fail if we had not called setActivePasswordState() again after
4225 // initializeDpms() - see previous comment.
4226 assertFalse(dpm.isActivePasswordSufficient());
4227
4228 initializeDpms();
4229 reset(mContext.spiedContext);
4230 assertFalse(dpm.isActivePasswordSufficient());
4231
4232 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4233 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4234 7, 2,
4235 5, 1,
4236 1, 2);
4237
4238 setActivePasswordState(passwordMetricsWithSymbols);
4239 assertTrue(dpm.isActivePasswordSufficient());
4240 }
4241
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004242 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4243 // If there is no lock screen, the password is considered empty no matter what, because
4244 // it provides no security.
4245 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4246
4247 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4248 mContext.packageName = admin1.getPackageName();
4249 setupDeviceOwner();
4250
4251 // If no password requirements are set, isActivePasswordSufficient should succeed.
4252 assertTrue(dpm.isActivePasswordSufficient());
4253
4254 // Now set some password quality requirements.
4255 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4256
4257 reset(mContext.spiedContext);
4258 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4259 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4260 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4261 8, 2,
4262 6, 1,
4263 0, 1);
4264 // This should be ignored, as there is no lock screen.
4265 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4266 dpm.reportPasswordChanged(userHandle);
4267
4268 // No broadcast should be sent.
4269 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4270 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4271 MockUtils.checkUserHandle(userHandle));
4272
4273 // The active (nonexistent) password doesn't comply with the requirements.
4274 assertFalse(dpm.isActivePasswordSufficient());
4275 }
4276
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4278 throws Exception {
4279 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004280 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004281
Pavel Grafov75c0a892017-05-18 17:28:27 +01004282 dpm.setActivePasswordState(passwordMetrics, userHandle);
4283 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004284
Rubin Xucc391c22018-01-02 20:37:35 +00004285 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4286 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004287 // This broadcast should be sent 4 times:
4288 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4289 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4290 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4291 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4292 // the password change is relevant to and another with the credential owner of said
4293 // userId.
4294 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004295 MockUtils.checkIntentAction(
4296 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4297 MockUtils.checkUserHandle(userHandle));
4298
Pavel Grafov75c0a892017-05-18 17:28:27 +01004299 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4300 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004301 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004302
4303 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4304 MockUtils.checkIntent(intent),
4305 MockUtils.checkUserHandle(userHandle));
4306
4307 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4308 // let it finish with system uid, otherwise it will throw and crash.
4309 flushTasks();
4310
4311 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004312 }
4313
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004314 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4315 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4316 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4317 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4318 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4319 DpmMockContext.SYSTEM_UID);
4320 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4321 DpmMockContext.SYSTEM_UID);
4322
4323 // Set up a device owner.
4324 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004325 setupDeviceOwner();
4326
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004327 // First and second user set IMEs manually.
4328 mContext.binder.callingUid = firstUserSystemUid;
4329 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4330 mContext.binder.callingUid = secondUserSystemUid;
4331 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004332
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004333 // Device owner changes IME for first user.
4334 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004335 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004336 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004337 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004338 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004339 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004340 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004341 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4342 mContext.binder.callingUid = firstUserSystemUid;
4343 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4344 mContext.binder.callingUid = secondUserSystemUid;
4345 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004346
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004347 // Second user changes IME manually.
4348 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4349 mContext.binder.callingUid = firstUserSystemUid;
4350 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4351 mContext.binder.callingUid = secondUserSystemUid;
4352 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004353
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004354 // First user changes IME manually.
4355 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4356 mContext.binder.callingUid = firstUserSystemUid;
4357 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4358 mContext.binder.callingUid = secondUserSystemUid;
4359 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004360
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004361 // Device owner changes IME for first user again.
4362 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004363 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004364 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004365 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004366 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004367 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004368 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4369 mContext.binder.callingUid = firstUserSystemUid;
4370 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4371 mContext.binder.callingUid = secondUserSystemUid;
4372 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004373
4374 // Restarting the DPMS should not lose information.
4375 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004376 mContext.binder.callingUid = firstUserSystemUid;
4377 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4378 mContext.binder.callingUid = secondUserSystemUid;
4379 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004380
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 // Device owner can find out whether it set the current IME itself.
4382 mContext.binder.callingUid = deviceOwnerUid;
4383 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004384
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004385 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004386 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004387 mContext.binder.callingUid = firstUserSystemUid;
4388 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4389 mContext.binder.callingUid = secondUserSystemUid;
4390 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004391 }
4392
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004393 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4394 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4395 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4396 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4397 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4398 DpmMockContext.SYSTEM_UID);
4399 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4400 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004401
4402 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004403 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004404 setupProfileOwner();
4405
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004406 // First and second user set IMEs manually.
4407 mContext.binder.callingUid = firstUserSystemUid;
4408 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4409 mContext.binder.callingUid = secondUserSystemUid;
4410 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004411
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004412 // Profile owner changes IME for second user.
4413 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004414 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004415 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004416 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004417 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004418 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004419 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004420 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4421 mContext.binder.callingUid = firstUserSystemUid;
4422 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4423 mContext.binder.callingUid = secondUserSystemUid;
4424 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004425
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004426 // First user changes IME manually.
4427 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4428 mContext.binder.callingUid = firstUserSystemUid;
4429 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4430 mContext.binder.callingUid = secondUserSystemUid;
4431 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004432
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004433 // Second user changes IME manually.
4434 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4435 mContext.binder.callingUid = firstUserSystemUid;
4436 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4437 mContext.binder.callingUid = secondUserSystemUid;
4438 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004439
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004440 // Profile owner changes IME for second user again.
4441 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004442 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004443 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004444 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004445 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004446 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004447 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4448 mContext.binder.callingUid = firstUserSystemUid;
4449 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4450 mContext.binder.callingUid = secondUserSystemUid;
4451 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004452
4453 // Restarting the DPMS should not lose information.
4454 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004455 mContext.binder.callingUid = firstUserSystemUid;
4456 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4457 mContext.binder.callingUid = secondUserSystemUid;
4458 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004460 // Profile owner can find out whether it set the current IME itself.
4461 mContext.binder.callingUid = profileOwnerUid;
4462 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004463
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004464 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004465 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004466 mContext.binder.callingUid = firstUserSystemUid;
4467 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4468 mContext.binder.callingUid = secondUserSystemUid;
4469 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004470 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004471
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004472 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4473 throws Exception {
4474 // Set up a device owner.
4475 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4476 setupDeviceOwner();
4477 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4478 }
4479
4480 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4481 throws Exception {
4482 // Set up a profile owner.
4483 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4484 setupProfileOwner();
4485 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4486 }
4487
4488 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4489 int adminUid) throws Exception {
4490 mContext.binder.callingUid = adminUid;
4491 final int userId = UserHandle.getUserId(adminUid);
4492
4493 final String packageName = "some.package";
4494 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4495 admin1, Collections.singletonList(packageName)));
4496 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4497
4498 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4499 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4500
4501 // Attempt to set to empty list (which means no listener is whitelisted)
4502 mContext.binder.callingUid = adminUid;
4503 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004504 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004505 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4506
4507 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4508 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4509 }
4510
4511 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4512 // Set up a managed profile
4513 final int MANAGED_PROFILE_USER_ID = 15;
4514 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4515 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4516 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4517
4518 final String permittedListener = "some.package";
4519 setupPackageInPackageManager(
4520 permittedListener,
4521 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4522 /*appId=*/ 12345, /*flags=*/ 0);
4523
4524 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4525 admin1, Collections.singletonList(permittedListener)));
4526
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004527 // isNotificationListenerServicePermitted should throw if not called from System.
4528 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4529 () -> dpms.isNotificationListenerServicePermitted(
4530 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004531
4532 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4533 assertTrue(dpms.isNotificationListenerServicePermitted(
4534 permittedListener, MANAGED_PROFILE_USER_ID));
4535 }
4536
4537 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4538 throws Exception {
4539 // Set up a managed profile
4540 final int MANAGED_PROFILE_USER_ID = 15;
4541 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4542 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4543 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4544
4545 final String permittedListener = "permitted.package";
4546 int appId = 12345;
4547 setupPackageInPackageManager(
4548 permittedListener,
4549 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4550 appId, /*flags=*/ 0);
4551
4552 final String notPermittedListener = "not.permitted.package";
4553 setupPackageInPackageManager(
4554 notPermittedListener,
4555 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4556 ++appId, /*flags=*/ 0);
4557
4558 final String systemListener = "system.package";
4559 setupPackageInPackageManager(
4560 systemListener,
4561 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4562 ++appId, ApplicationInfo.FLAG_SYSTEM);
4563
4564 // By default all packages are allowed
4565 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4566
4567 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4568 assertTrue(dpms.isNotificationListenerServicePermitted(
4569 permittedListener, MANAGED_PROFILE_USER_ID));
4570 assertTrue(dpms.isNotificationListenerServicePermitted(
4571 notPermittedListener, MANAGED_PROFILE_USER_ID));
4572 assertTrue(dpms.isNotificationListenerServicePermitted(
4573 systemListener, MANAGED_PROFILE_USER_ID));
4574
4575 // Setting only one package in the whitelist
4576 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4577 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4578 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004579 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004580 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4581 assertEquals(1, permittedListeners.size());
4582 assertEquals(permittedListener, permittedListeners.get(0));
4583
4584 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4585 assertTrue(dpms.isNotificationListenerServicePermitted(
4586 permittedListener, MANAGED_PROFILE_USER_ID));
4587 assertFalse(dpms.isNotificationListenerServicePermitted(
4588 notPermittedListener, MANAGED_PROFILE_USER_ID));
4589 // System packages are always allowed (even if not in the whitelist)
4590 assertTrue(dpms.isNotificationListenerServicePermitted(
4591 systemListener, MANAGED_PROFILE_USER_ID));
4592
4593 // Setting an empty whitelist - only system listeners allowed
4594 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4595 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004596 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004597 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4598
4599 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4600 assertFalse(dpms.isNotificationListenerServicePermitted(
4601 permittedListener, MANAGED_PROFILE_USER_ID));
4602 assertFalse(dpms.isNotificationListenerServicePermitted(
4603 notPermittedListener, MANAGED_PROFILE_USER_ID));
4604 // System packages are always allowed (even if not in the whitelist)
4605 assertTrue(dpms.isNotificationListenerServicePermitted(
4606 systemListener, MANAGED_PROFILE_USER_ID));
4607
4608 // Setting a null whitelist - all listeners allowed
4609 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4610 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4611 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4612
4613 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4614 assertTrue(dpms.isNotificationListenerServicePermitted(
4615 permittedListener, MANAGED_PROFILE_USER_ID));
4616 assertTrue(dpms.isNotificationListenerServicePermitted(
4617 notPermittedListener, MANAGED_PROFILE_USER_ID));
4618 assertTrue(dpms.isNotificationListenerServicePermitted(
4619 systemListener, MANAGED_PROFILE_USER_ID));
4620 }
4621
4622 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4623 throws Exception {
4624 // Set up a managed profile
4625 final int MANAGED_PROFILE_USER_ID = 15;
4626 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4627 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4628 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4629
4630 final String nonSystemPackage = "non.system.package";
4631 int appId = 12345;
4632 setupPackageInPackageManager(
4633 nonSystemPackage,
4634 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4635 appId, /*flags=*/ 0);
4636
4637 final String systemListener = "system.package";
4638 setupPackageInPackageManager(
4639 systemListener,
4640 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4641 ++appId, ApplicationInfo.FLAG_SYSTEM);
4642
4643 // By default all packages are allowed (for all profiles)
4644 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4645
4646 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4647 assertTrue(dpms.isNotificationListenerServicePermitted(
4648 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4649 assertTrue(dpms.isNotificationListenerServicePermitted(
4650 systemListener, MANAGED_PROFILE_USER_ID));
4651 assertTrue(dpms.isNotificationListenerServicePermitted(
4652 nonSystemPackage, UserHandle.USER_SYSTEM));
4653 assertTrue(dpms.isNotificationListenerServicePermitted(
4654 systemListener, UserHandle.USER_SYSTEM));
4655
4656 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4657 // all allowed in primary profile
4658 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4659 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004660 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004661 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4662
4663 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4664 assertFalse(dpms.isNotificationListenerServicePermitted(
4665 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4666 assertTrue(dpms.isNotificationListenerServicePermitted(
4667 systemListener, MANAGED_PROFILE_USER_ID));
4668 assertTrue(dpms.isNotificationListenerServicePermitted(
4669 nonSystemPackage, UserHandle.USER_SYSTEM));
4670 assertTrue(dpms.isNotificationListenerServicePermitted(
4671 systemListener, UserHandle.USER_SYSTEM));
4672 }
4673
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004674 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004675 mServiceContext.packageName = mRealTestContext.getPackageName();
4676 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4677 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004678 setDeviceOwner();
4679
Pavel Grafov75c0a892017-05-18 17:28:27 +01004680 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004681 }
4682
4683 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004684 mServiceContext.packageName = mRealTestContext.getPackageName();
4685 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4686 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004687 setAsProfileOwner(admin1);
4688
Pavel Grafov75c0a892017-05-18 17:28:27 +01004689 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4690 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004691 }
4692
4693 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004694 mServiceContext.packageName = mRealTestContext.getPackageName();
4695 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4696 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004697 setAsProfileOwner(admin1);
4698
Pavel Grafov75c0a892017-05-18 17:28:27 +01004699 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4700 caller.packageName = "com.example.delegate";
4701 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4702 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004703
Pavel Grafov75c0a892017-05-18 17:28:27 +01004704 // Make caller a delegated cert installer.
4705 runAsCaller(mAdmin1Context, dpms,
4706 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004707
4708 verifyCanGetOwnerInstalledCaCerts(null, caller);
4709 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004710 }
4711
Rubin Xucc391c22018-01-02 20:37:35 +00004712 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004713 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4714 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004715 Bundle restriction = new Bundle();
4716 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4717
4718 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4719 RestrictionsListener listener = new RestrictionsListener(mContext);
4720 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4721 new Bundle());
4722 verifyDataSharingChangedBroadcast();
4723 }
4724
4725 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004726 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4727 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004728 Bundle restriction = new Bundle();
4729 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4730
4731 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4732 RestrictionsListener listener = new RestrictionsListener(mContext);
4733 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4734 restriction);
4735 verifyDataSharingChangedBroadcast();
4736 }
4737
4738 public void testDisallowSharingIntoProfileUnchanged() {
4739 RestrictionsListener listener = new RestrictionsListener(mContext);
4740 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4741 new Bundle());
4742 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4743 }
4744
4745 private void verifyDataSharingChangedBroadcast() {
4746 Intent expectedIntent = new Intent(
4747 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4748 expectedIntent.setPackage("com.android.managedprovisioning");
4749 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4750 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4751 MockUtils.checkIntent(expectedIntent),
4752 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4753 }
4754
yuemingwe3d9c092018-01-11 12:11:44 +00004755 public void testOverrideApnAPIsFailWithPO() throws Exception {
4756 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004757 ApnSetting apn = (new ApnSetting.Builder())
4758 .setApnName("test")
4759 .setEntryName("test")
4760 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4761 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004762 assertExpectException(SecurityException.class, null, () ->
4763 dpm.addOverrideApn(admin1, apn));
4764 assertExpectException(SecurityException.class, null, () ->
4765 dpm.updateOverrideApn(admin1, 0, apn));
4766 assertExpectException(SecurityException.class, null, () ->
4767 dpm.removeOverrideApn(admin1, 0));
4768 assertExpectException(SecurityException.class, null, () ->
4769 dpm.getOverrideApns(admin1));
4770 assertExpectException(SecurityException.class, null, () ->
4771 dpm.setOverrideApnsEnabled(admin1, false));
4772 assertExpectException(SecurityException.class, null, () ->
4773 dpm.isOverrideApnEnabled(admin1));
4774 }
4775
Robin Lee2c68dad2017-03-17 12:50:24 +00004776 private void verifyCanGetOwnerInstalledCaCerts(
4777 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004778 final String alias = "cert";
4779 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004780
4781 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004782 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004783 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4784 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004785 }
4786 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4787
4788 // caller: device admin or delegated certificate installer
4789 callerContext.applicationInfo = new ApplicationInfo();
4790 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4791
4792 // system_server
4793 final DpmMockContext serviceContext = mContext;
4794 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 getServices().addPackageContext(callerUser, admin1Context);
4796 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004797
4798 // Install a CA cert.
4799 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004800 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004801 .thenReturn(alias);
4802 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004803 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004804 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004805 });
4806
Pavel Grafov75c0a892017-05-18 17:28:27 +01004807 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4808 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4809 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004810 flushTasks();
4811
Robin Lee2c68dad2017-03-17 12:50:24 +00004812 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4813
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004814 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004815 runAsCaller(admin1Context, dpms, (dpm) -> {
4816 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004817 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004818 ownerInstalledCaCerts.addAll(installedCaCerts);
4819 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004820
4821 // Restarting the DPMS should not lose information.
4822 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004823 runAsCaller(admin1Context, dpms, (dpm) ->
4824 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004825
4826 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004827 runAsCaller(serviceContext, dpms, (dpm) -> {
4828 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004829
Robin Lee2c68dad2017-03-17 12:50:24 +00004830 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004831 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004832 });
4833
Pavel Grafov75c0a892017-05-18 17:28:27 +01004834 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4835 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4836 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004837 flushTasks();
4838
4839 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4840 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004841 runAsCaller(admin1Context, dpms, (dpm) -> {
4842 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4843 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004844 }
4845
Robin Lee2c68dad2017-03-17 12:50:24 +00004846 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4847 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004848 final String alias = "cert";
4849 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004850
4851 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004852 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004853 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4854 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004855 }
4856 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4857
4858 // caller: device admin or delegated certificate installer
4859 callerContext.applicationInfo = new ApplicationInfo();
4860 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4861
4862 // system_server
4863 final DpmMockContext serviceContext = mContext;
4864 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004865 getServices().addPackageContext(callerUser, admin1Context);
4866 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004867
4868 // Install a CA cert as caller
4869 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004870 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004871 .thenReturn(alias);
4872 assertTrue(dpm.installCaCert(callerName, caCert));
4873 });
4874
4875 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004876 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004877 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004878 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4879 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4880 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004881 flushTasks();
4882
Robin Lee2c68dad2017-03-17 12:50:24 +00004883 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004884 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004885
4886 runAsCaller(serviceContext, dpms, (dpm) -> {
4887 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4888 assertNotNull(ownerInstalledCaCerts);
4889 assertTrue(ownerInstalledCaCerts.isEmpty());
4890 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004891 }
4892
Eran Messeri94d56762017-12-21 20:50:54 +00004893 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4894 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4895 Arrays.sort(gotFlags);
4896 Arrays.sort(expectedFlags);
4897 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4898 }
4899
4900 public void testTranslationOfIdAttestationFlag() {
4901 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4902 int[] correspondingAttUtilsTypes = new int[]{
4903 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4904 AttestationUtils.ID_TYPE_MEID};
4905
4906 // Test translation of zero flags
4907 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4908
4909 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4910 // non-null array
4911 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4912
4913 // Test translation of a single flag
4914 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4915 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4916 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4917
4918 // Test translation of two flags
4919 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4920 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4921 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4922 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4923
4924 // Test translation of all three flags
4925 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4926 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4927 AttestationUtils.ID_TYPE_MEID});
4928 // Test translation of all three flags
4929 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4930 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4931 AttestationUtils.ID_TYPE_MEID});
4932 }
4933
arangelov08d534b2018-01-22 15:20:53 +00004934 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4935 setDeviceOwner();
4936 initializeDpms();
4937 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4938 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4939 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4940 }
4941
4942 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4943 DpmTestUtils.writeInputStreamToFile(
4944 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4945 getDeviceOwnerPoliciesFile());
4946 DpmTestUtils.writeInputStreamToFile(
4947 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4948 getDeviceOwnerFile());
4949 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4950 }
4951
4952 public void testRevertDeviceOwnership_deviceNotMigrated()
4953 throws Exception {
4954 DpmTestUtils.writeInputStreamToFile(
4955 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4956 getDeviceOwnerPoliciesFile());
4957 DpmTestUtils.writeInputStreamToFile(
4958 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4959 getDeviceOwnerFile());
4960 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4961 }
4962
4963 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4964 throws Exception {
4965 DpmTestUtils.writeInputStreamToFile(
4966 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4967 getDeviceOwnerPoliciesFile());
4968 DpmTestUtils.writeInputStreamToFile(
4969 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4970 getDeviceOwnerFile());
4971 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4972 }
4973
4974 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4975 setupProfileOwner();
4976 initializeDpms();
4977 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4978 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4979 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4980 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4981 }
4982
4983 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4984 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4985 UserHandle.USER_SYSTEM);
4986 DpmTestUtils.writeInputStreamToFile(
4987 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4988 getProfileOwnerPoliciesFile());
4989 DpmTestUtils.writeInputStreamToFile(
4990 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4991 getProfileOwnerFile());
4992 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4993 }
4994
4995 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4996 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4997 UserHandle.USER_SYSTEM);
4998 DpmTestUtils.writeInputStreamToFile(
4999 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5000 getProfileOwnerPoliciesFile());
5001 DpmTestUtils.writeInputStreamToFile(
5002 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5003 getProfileOwnerFile());
5004 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5005 }
5006
5007 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5008 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5009 UserHandle.USER_SYSTEM);
5010 DpmTestUtils.writeInputStreamToFile(
5011 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5012 getProfileOwnerPoliciesFile());
5013 DpmTestUtils.writeInputStreamToFile(
5014 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5015 getProfileOwnerFile());
5016 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5017 }
5018
Eran Messeribb271892018-10-17 18:27:50 +01005019 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5020 setupProfileOwner();
5021 configureContextForAccess(mContext, false);
5022
5023 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5024 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin2,
5025 UserHandle.of(DpmMockContext.CALLER_UID)));
5026 }
5027
5028 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5029 setupProfileOwner();
5030 configureContextForAccess(mContext, false);
5031
5032 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5033 () -> dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5034 UserHandle.of(DpmMockContext.CALLER_UID)));
5035 }
5036
5037 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5038 setupProfileOwner();
5039
5040 // This method will throw if the system context could not call
5041 // setProfileOwnerCanAccessDeviceIds successfully.
5042 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5043 }
5044
5045 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5046 when(context.spiedContext.checkCallingPermission(
5047 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5048 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5049 : PackageManager.PERMISSION_DENIED);
5050 }
5051
5052 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5053 setupProfileOwner();
5054
5055 final long ident = mServiceContext.binder.clearCallingIdentity();
5056 configureContextForAccess(mServiceContext, true);
5057
5058 mServiceContext.binder.callingUid =
5059 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5060 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5061 try {
5062 runAsCaller(mServiceContext, dpms, dpm -> {
5063 dpm.setProfileOwnerCanAccessDeviceIdsForUser(admin1,
5064 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE));
5065 });
5066 } finally {
5067 mServiceContext.binder.restoreCallingIdentity(ident);
5068 }
5069 }
5070
5071 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5072 throws Exception {
5073 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5074 setupDeviceOwner();
5075 configureContextForAccess(mContext, false);
5076
5077 // Device owner should be allowed to request Device ID attestation.
5078 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5079 DpmMockContext.CALLER_SYSTEM_USER_UID);
5080
5081 // Another package must not be allowed to request Device ID attestation.
5082 assertExpectException(SecurityException.class, null,
5083 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5084 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5085 // Another component that is not the admin must not be allowed to request Device ID
5086 // attestation.
5087 assertExpectException(SecurityException.class, null,
5088 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5089 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5090 }
5091
5092 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5093 throws Exception {
5094 configureContextForAccess(mContext, false);
5095
5096 // Make sure a security exception is thrown if the device has no profile owner.
5097 assertExpectException(SecurityException.class, null,
5098 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5099 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5100
5101 setupProfileOwner();
5102 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5103
5104 // The profile owner is allowed to request Device ID attestation.
5105 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5106 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5107 DpmMockContext.CALLER_UID);
5108 // But not another package.
5109 assertExpectException(SecurityException.class, null,
5110 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5111 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5112 // Or another component which is not the admin.
5113 assertExpectException(SecurityException.class, null,
5114 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5115 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5116 }
5117
5118 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5119 final long ident = mServiceContext.binder.clearCallingIdentity();
5120
5121 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5122 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5123 try {
5124 runAsCaller(mServiceContext, dpms, action);
5125 } finally {
5126 mServiceContext.binder.restoreCallingIdentity(ident);
5127 }
5128 }
5129
5130 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5131 setupProfileOwner();
5132 markDelegatedCertInstallerAsInstalled();
5133
5134 // Configure a delegated cert installer.
5135 runAsCaller(mServiceContext, dpms,
5136 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5137 Arrays.asList(DELEGATION_CERT_INSTALL)));
5138
5139 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5140
5141 // Make sure that the profile owner can still request Device ID attestation.
5142 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5143 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5144 DpmMockContext.CALLER_UID);
5145
5146 runAsDelegatedCertInstaller(dpm -> {
5147 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5148 DpmMockContext.DELEGATE_PACKAGE_NAME,
5149 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5150 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5151 });
5152 }
5153
5154 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5155 throws Exception {
5156 setupProfileOwner();
5157 markDelegatedCertInstallerAsInstalled();
5158
5159 // Configure a delegated cert installer.
5160 runAsCaller(mServiceContext, dpms,
5161 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5162 Arrays.asList(DELEGATION_CERT_INSTALL)));
5163
5164
5165 assertExpectException(SecurityException.class, null,
5166 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5167 admin1.getPackageName(),
5168 DpmMockContext.CALLER_UID));
5169
5170 runAsDelegatedCertInstaller(dpm -> {
5171 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5172 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5173 DpmMockContext.DELEGATE_PACKAGE_NAME,
5174 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5175 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5176 });
5177 }
5178
Bernard Chaue9586552018-11-29 10:59:31 +00005179 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5180 assertThrows(SecurityException.class,
5181 () -> new DevicePolicyManagerTestable(
5182 mServiceContext,
5183 dpms,
5184 /* parentInstance= */ true)
5185 .getPasswordComplexity());
5186 }
5187
5188 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5189 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5190 .thenReturn(false);
5191 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5192 }
5193
5194 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5195 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5196 .thenReturn(true);
5197 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5198 }
5199
5200
5201 public void testGetPasswordComplexity_currentUserNoPassword() {
5202 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5203 .thenReturn(true);
Bernard Chau09121902019-02-08 15:48:35 +00005204 mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005205 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5206 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5207
5208 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5209 }
5210
5211 public void testGetPasswordComplexity_currentUserHasPassword() {
5212 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5213 .thenReturn(true);
Bernard Chau09121902019-02-08 15:48:35 +00005214 mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005215 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5216 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5217 dpms.mUserPasswordMetrics.put(
5218 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005219 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005220
5221 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5222 }
5223
5224 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5225 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5226 .thenReturn(true);
Bernard Chau09121902019-02-08 15:48:35 +00005227 mServiceContext.permissions.add(permission.REQUEST_SCREEN_LOCK_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005228
5229 UserInfo parentUser = new UserInfo();
5230 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5231 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5232 .thenReturn(parentUser.id);
5233
5234 dpms.mUserPasswordMetrics.put(
5235 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005236 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005237 dpms.mUserPasswordMetrics.put(
5238 parentUser.id,
Rich Canningsf64ec632019-02-21 12:40:36 -08005239 PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005240
5241 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5242 }
5243
yuemingwd2bfbc82019-01-02 11:42:25 +00005244 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5245 setAsProfileOwner(admin1);
5246 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5247 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5248 }
5249
5250 public void testCrossProfileCalendarPackages_reopenDpms() {
5251 setAsProfileOwner(admin1);
5252 dpm.setCrossProfileCalendarPackages(admin1, null);
5253 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5254 assertTrue(packages == null);
5255 initializeDpms();
5256 packages = dpm.getCrossProfileCalendarPackages(admin1);
5257 assertTrue(packages == null);
5258
5259 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5260 packages = dpm.getCrossProfileCalendarPackages(admin1);
5261 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5262 initializeDpms();
5263 packages = dpm.getCrossProfileCalendarPackages(admin1);
5264 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5265
5266 final String dummyPackageName = "test";
5267 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5268 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5269 packages = dpm.getCrossProfileCalendarPackages(admin1);
5270 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5271 initializeDpms();
5272 packages = dpm.getCrossProfileCalendarPackages(admin1);
5273 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5274 }
5275
5276 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5277 assertTrue(expected != null);
5278 assertTrue(actual != null);
5279 assertTrue(expected.containsAll(actual));
5280 assertTrue(actual.containsAll(expected));
5281 }
5282
yuemingwdded98f2019-01-30 17:08:12 +00005283 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5284 setAsProfileOwner(admin1);
5285 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5286 when(getServices().settings.settingsSecureGetIntForUser(
5287 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5288 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5289 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5290 }
5291
5292 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5293 final String testPackage = "TEST_PACKAGE";
5294 setAsProfileOwner(admin1);
5295 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5296 when(getServices().settings.settingsSecureGetIntForUser(
5297 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5298 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5299 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5300 }
5301
5302 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5303 final String testPackage = "TEST_PACKAGE";
5304 setAsProfileOwner(admin1);
5305 dpm.setCrossProfileCalendarPackages(admin1, null);
5306 when(getServices().settings.settingsSecureGetIntForUser(
5307 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5308 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5309 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5310 }
5311
Eran Messeribb271892018-10-17 18:27:50 +01005312 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5313 final long ident = mServiceContext.binder.clearCallingIdentity();
5314 mServiceContext.binder.callingUid =
5315 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5316 runAsCaller(mServiceContext, dpms, dpm -> {
5317 dpm.setProfileOwnerCanAccessDeviceIdsForUser(who, UserHandle.of(userId));
5318 });
5319 mServiceContext.binder.restoreCallingIdentity(ident);
5320 }
5321
arangelov08d534b2018-01-22 15:20:53 +00005322 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5323 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5324 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5325 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5326
5327 final long ident = mServiceContext.binder.clearCallingIdentity();
5328 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5329 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5330 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5331 // To simulate a reboot, we just reinitialize dpms and call systemReady
5332 initializeDpms();
5333
5334 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5335 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5336 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5337 assertTrue(dpm.isAdminActive(admin1));
5338 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5339 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5340
5341 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5342 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5343 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5344 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5345
5346 mServiceContext.binder.restoreCallingIdentity(ident);
5347 }
5348
5349 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5350 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5351 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5352 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5353
5354 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5355 DpmMockContext.CALLER_SYSTEM_USER_UID);
5356 setUpPackageManagerForAdmin(admin1, uid);
5357 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5358 // To simulate a reboot, we just reinitialize dpms and call systemReady
5359 initializeDpms();
5360
5361 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5362 assertTrue(dpm.isAdminActive(admin1));
5363 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5364 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5365 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5366 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5367 }
5368
5369 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5370 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5371 metadataManager.deleteMetadataFile();
5372
5373 final TransferOwnershipMetadataManager.Metadata metadata =
5374 new TransferOwnershipMetadataManager.Metadata(
5375 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5376 callerUserHandle,
5377 adminType);
5378 metadataManager.saveMetadataFile(metadata);
5379 }
5380
5381 private File getDeviceOwnerFile() {
5382 return dpms.mOwners.getDeviceOwnerFile();
5383 }
5384
5385 private File getProfileOwnerFile() {
5386 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5387 }
5388
5389 private File getProfileOwnerPoliciesFile() {
5390 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5391 DpmMockContext.CALLER_USER_HANDLE);
5392 return getPoliciesFile(parentDir);
5393 }
5394
5395 private File getDeviceOwnerPoliciesFile() {
5396 return getPoliciesFile(getServices().systemUserDataDir);
5397 }
5398
5399 private File getPoliciesFile(File parentDir) {
5400 return new File(parentDir, "device_policies.xml");
5401 }
5402
5403 private InputStream getRawStream(@RawRes int id) {
5404 return mRealTestContext.getResources().openRawResource(id);
5405 }
5406
Victor Chang3e794af2016-03-04 13:48:17 +00005407 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005408 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005409 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5410 dpms.notifyChangeToContentObserver(
5411 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5412 }
5413
5414 private void assertProvisioningAllowed(String action, boolean expected) {
5415 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5416 dpm.isProvisioningAllowed(action));
5417 }
Tony Mak2f26b792016-11-28 17:54:51 +00005418
Nicolas Prevot45d29072017-01-18 16:11:19 +00005419 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5420 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005421 final String previousPackageName = mContext.packageName;
5422 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005423
5424 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5425 mContext.packageName = packageName;
5426 mMockContext.binder.callingUid = uid;
5427 assertProvisioningAllowed(action, expected);
5428
5429 // Set the previous package name / calling uid to go back to the initial state.
5430 mContext.packageName = previousPackageName;
5431 mMockContext.binder.callingUid = previousUid;
5432 }
5433
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005434 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005435 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5436 }
5437
5438 private void assertCheckProvisioningPreCondition(
5439 String action, String packageName, int provisioningCondition) {
5440 assertEquals("checkProvisioningPreCondition("
5441 + action + ", " + packageName + ") returning unexpected result",
5442 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005443 }
5444
Tony Mak2f26b792016-11-28 17:54:51 +00005445 /**
5446 * Setup a managed profile with the specified admin and its uid.
5447 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5448 * @param adminUid uid of the admin package.
5449 * @param copyFromAdmin package information for {@code admin} will be built based on this
5450 * component's information.
5451 */
5452 private void addManagedProfile(
5453 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5454 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005455 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005456 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5457 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5458 dpm.setActiveAdmin(admin, false, userId);
5459 assertTrue(dpm.setProfileOwner(admin, null, userId));
5460 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5461 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005462
5463 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005464 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005465 */
Robin Leeabaa0692017-02-20 20:54:22 +00005466 private static StringParceledListSlice asSlice(String[] s) {
5467 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005468 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005469
5470 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005471 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5472 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005473
Robin Lee2c68dad2017-03-17 12:50:24 +00005474 // We can't let exceptions happen on the background thread. Throw them here if they happen
5475 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005476 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005477 }
Victor Chang3e794af2016-03-04 13:48:17 +00005478}