blob: 5da2a8548fb36490491e697d8dd76dabc8dbcf20 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
yinxuf4f9cec2017-06-19 10:28:19 -070024import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010025import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
26import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
27import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
28
Eugene Susla4f8680b2017-08-07 17:25:30 -070029import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010030
Pavel Grafov75c0a892017-05-18 17:28:27 +010031import static org.mockito.Matchers.any;
32import static org.mockito.Matchers.anyInt;
33import static org.mockito.Matchers.anyLong;
34import static org.mockito.Matchers.anyObject;
35import static org.mockito.Matchers.anyString;
36import static org.mockito.Matchers.eq;
37import static org.mockito.Matchers.isNull;
38import static org.mockito.Mockito.atLeast;
39import static org.mockito.Mockito.doAnswer;
40import static org.mockito.Mockito.doReturn;
41import static org.mockito.Mockito.never;
42import static org.mockito.Mockito.nullable;
43import static org.mockito.Mockito.reset;
44import static org.mockito.Mockito.timeout;
45import static org.mockito.Mockito.times;
46import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080047import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010048import static org.mockito.Mockito.verifyZeroInteractions;
49import static org.mockito.Mockito.when;
50import static org.mockito.hamcrest.MockitoHamcrest.argThat;
51
Makoto Onukif76b06a2015-09-22 15:03:44 -070052import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000053import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070054import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000055import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070056import android.app.admin.DeviceAdminReceiver;
57import android.app.admin.DevicePolicyManager;
58import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010059import android.app.admin.PasswordMetrics;
Lenka Trochtova56681f72018-03-09 15:47:50 +010060import android.app.backup.ISelectBackupTransportCallback;
Makoto Onukif76b06a2015-09-22 15:03:44 -070061import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000063import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000064import android.content.pm.ApplicationInfo;
65import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010067import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000068import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000069import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010070import android.graphics.Color;
71import android.net.Uri;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080072import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080073import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070074import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080075import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070076import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070077import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010078import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080079import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010080import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000081import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000082import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000083import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080084import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000085import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010086import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070087import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010089import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000090import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000091import com.android.server.LocalServices;
92import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000093import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000094import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000095
Robin Lee7f5c91c2017-02-08 21:27:02 +000096import org.hamcrest.BaseMatcher;
97import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -080098import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -070099import org.mockito.invocation.InvocationOnMock;
100import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101
arangelov08d534b2018-01-22 15:20:53 +0000102import java.io.File;
103import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800104import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000105import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000106import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700107import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700109import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100110import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000111import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700114 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000115 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116 m FrameworksServicesTests &&
117 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000118 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800120 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121
122 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000123 *
124 * , or:
125 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000127@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100128@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000130 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
131 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
132 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100133 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800134 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100135 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000136
Pavel Grafov75c0a892017-05-18 17:28:27 +0100137 // TODO replace all instances of this with explicit {@link #mServiceContext}.
138 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700139 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100140
141 private DpmMockContext mServiceContext;
142 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700143 public DevicePolicyManager dpm;
144 public DevicePolicyManagerServiceTestable dpms;
145
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100146 /*
147 * The CA cert below is the content of cacert.pem as generated by:
148 *
149 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
150 */
151 private static final String TEST_CA =
152 "-----BEGIN CERTIFICATE-----\n" +
153 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
154 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
155 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
156 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
157 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
158 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
159 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
160 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
161 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
162 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
163 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
164 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
165 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
166 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
167 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
168 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
169 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
170 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
171 "wQ==\n" +
172 "-----END CERTIFICATE-----\n";
173
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700174 @Override
175 protected void setUp() throws Exception {
176 super.setUp();
177
178 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100179 mServiceContext = mContext;
180 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
181 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700182 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100183 doReturn(Collections.singletonList(new ResolveInfo()))
184 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
185 any(Intent.class),
186 anyInt(),
187 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700188
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800189 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100190 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800191
Makoto Onukia52562c2015-10-01 16:12:31 -0700192 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700193
Sudheer Shanka101c3532018-01-08 16:28:42 -0800194 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800195 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700196 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
197 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
198 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800199 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700200
Pavel Grafov75c0a892017-05-18 17:28:27 +0100201 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
202 mAdmin1Context.packageName = admin1.getPackageName();
203 mAdmin1Context.applicationInfo = new ApplicationInfo();
204 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
205
Makoto Onukib643fb02015-09-22 15:03:44 -0700206 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700207 }
208
arangelov08d534b2018-01-22 15:20:53 +0000209 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
210 return dpms.mTransferOwnershipMetadataManager;
211 }
212
Robin Lee2c68dad2017-03-17 12:50:24 +0000213 @Override
214 protected void tearDown() throws Exception {
215 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000216 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000217 super.tearDown();
218 }
219
Makoto Onukia52562c2015-10-01 16:12:31 -0700220 private void initializeDpms() {
221 // Need clearCallingIdentity() to pass permission checks.
222 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100223 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700224
Pavel Grafov75c0a892017-05-18 17:28:27 +0100225 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
226 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
227 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700228
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700230
Pavel Grafov75c0a892017-05-18 17:28:27 +0100231 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700232 }
233
Makoto Onukib643fb02015-09-22 15:03:44 -0700234 private void setUpUserManager() {
235 // Emulate UserManager.set/getApplicationRestriction().
236 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
237
238 // UM.setApplicationRestrictions() will save to appRestrictions.
239 doAnswer(new Answer<Void>() {
240 @Override
241 public Void answer(InvocationOnMock invocation) throws Throwable {
242 String pkg = (String) invocation.getArguments()[0];
243 Bundle bundle = (Bundle) invocation.getArguments()[1];
244 UserHandle user = (UserHandle) invocation.getArguments()[2];
245
246 appRestrictions.put(Pair.create(pkg, user), bundle);
247
248 return null;
249 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100250 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100251 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
253 // UM.getApplicationRestrictions() will read from appRestrictions.
254 doAnswer(new Answer<Bundle>() {
255 @Override
256 public Bundle answer(InvocationOnMock invocation) throws Throwable {
257 String pkg = (String) invocation.getArguments()[0];
258 UserHandle user = (UserHandle) invocation.getArguments()[1];
259
260 return appRestrictions.get(Pair.create(pkg, user));
261 }
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700263 anyString(), any(UserHandle.class));
264
Makoto Onukid932f762015-09-29 16:53:38 -0700265 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100266 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700267 }
268
269 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700271
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 mServiceContext.binder.callingUid =
273 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
274 runAsCaller(mServiceContext, dpms, dpm -> {
275 // PO needs to be a DA.
276 dpm.setActiveAdmin(admin, /*replace=*/ false);
277 // Fire!
278 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
279 // Check
280 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
281 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700282
Pavel Grafov75c0a892017-05-18 17:28:27 +0100283 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700284 }
285
286 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100287 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700288 .thenReturn(false);
289
290 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100291 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292
293 // If the device has no DPMS feature, it shouldn't register the local service.
294 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
295 }
296
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800297 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800298 // Device owner in SYSTEM_USER
299 setDeviceOwner();
300 // Profile owner in CALLER_USER_HANDLE
301 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
302 setAsProfileOwner(admin2);
303 // Active admin in CALLER_USER_HANDLE
304 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
305 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
306 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
307 DpmMockContext.CALLER_USER_HANDLE);
308 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
309 DpmMockContext.CALLER_USER_HANDLE));
310
311 initializeDpms();
312
313 // Verify
314 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800315 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800316 eq(UserHandle.USER_SYSTEM));
317 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800318 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800319 adminAnotherPackage.getPackageName()),
320 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800321 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
322 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
323 }
324
325 public void testLoadAdminData_noAdmins() throws Exception {
326 final int ANOTHER_USER_ID = 15;
327 getServices().addUser(ANOTHER_USER_ID, 0);
328
329 initializeDpms();
330
331 // Verify
332 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
333 null, DpmMockContext.CALLER_USER_HANDLE);
334 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
335 null, ANOTHER_USER_ID);
336 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
337 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800338 }
339
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700340 /**
341 * Caller doesn't have proper permissions.
342 */
343 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344 // 1. Failure cases.
345
346 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100347 assertExpectException(SecurityException.class, /* messageRegex= */ null,
348 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700349
350 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
351 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100352
353 assertExpectException(SecurityException.class, /* messageRegex= */ null,
354 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700355 }
356
Makoto Onukif76b06a2015-09-22 15:03:44 -0700357 /**
358 * Test for:
359 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800360 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 * {@link DevicePolicyManager#isAdminActive}
362 * {@link DevicePolicyManager#isAdminActiveAsUser}
363 * {@link DevicePolicyManager#getActiveAdmins}
364 * {@link DevicePolicyManager#getActiveAdminsAsUser}
365 */
366 public void testSetActiveAdmin() throws Exception {
367 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700368 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
369
Makoto Onukif76b06a2015-09-22 15:03:44 -0700370 // 2. Call the API.
371 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700372
373 // 3. Verify internal calls.
374
375 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700376 verify(mContext.spiedContext).sendBroadcastAsUser(
377 MockUtils.checkIntentAction(
378 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
379 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
380 verify(mContext.spiedContext).sendBroadcastAsUser(
381 MockUtils.checkIntentAction(
382 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700383 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
384
Pavel Grafov75c0a892017-05-18 17:28:27 +0100385 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700386 eq(admin1.getPackageName()),
387 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
388 eq(PackageManager.DONT_KILL_APP),
389 eq(DpmMockContext.CALLER_USER_HANDLE),
390 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700391
Sudheer Shanka101c3532018-01-08 16:28:42 -0800392 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
393 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
394
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700395 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700396
397 // Make sure it's active admin1.
398 assertTrue(dpm.isAdminActive(admin1));
399 assertFalse(dpm.isAdminActive(admin2));
400 assertFalse(dpm.isAdminActive(admin3));
401
402 // But not admin1 for a different user.
403
404 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
405 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
406 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
407
408 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
409 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
410
411 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
412
413 // Next, add one more admin.
414 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700415 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700416 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700417
418 dpm.setActiveAdmin(admin2, /* replace =*/ false);
419
420 // Now we have two admins.
421 assertTrue(dpm.isAdminActive(admin1));
422 assertTrue(dpm.isAdminActive(admin2));
423 assertFalse(dpm.isAdminActive(admin3));
424
425 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
426 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100427 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700428 eq(admin1.getPackageName()),
429 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
430 eq(PackageManager.DONT_KILL_APP),
431 eq(DpmMockContext.CALLER_USER_HANDLE),
432 anyString());
433
Sudheer Shanka101c3532018-01-08 16:28:42 -0800434 // times(2) because it was previously called for admin1 which is in the same package
435 // as admin2.
436 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
437 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
438
Makoto Onukif76b06a2015-09-22 15:03:44 -0700439 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100440 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
441 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442
443 // 5. Add the same admin1 again with replace, which should succeed.
444 dpm.setActiveAdmin(admin1, /* replace =*/ true);
445
446 // TODO make sure it's replaced.
447
448 // 6. Test getActiveAdmins()
449 List<ComponentName> admins = dpm.getActiveAdmins();
450 assertEquals(2, admins.size());
451 assertEquals(admin1, admins.get(0));
452 assertEquals(admin2, admins.get(1));
453
Sudheer Shanka101c3532018-01-08 16:28:42 -0800454 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
455 // replaced
456 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
457
Makoto Onukif76b06a2015-09-22 15:03:44 -0700458 // Another user has no admins.
459 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
460
461 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
462 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
463
464 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
465 }
466
Makoto Onukid932f762015-09-29 16:53:38 -0700467 public void testSetActiveAdmin_multiUsers() throws Exception {
468
469 final int ANOTHER_USER_ID = 100;
470 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
471
Pavel Grafov75c0a892017-05-18 17:28:27 +0100472 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700473
474 // Set up pacakge manager for the other user.
475 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
478
479 dpm.setActiveAdmin(admin1, /* replace =*/ false);
480
481 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
482 dpm.setActiveAdmin(admin2, /* replace =*/ false);
483
484
485 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
486 assertTrue(dpm.isAdminActive(admin1));
487 assertFalse(dpm.isAdminActive(admin2));
488
489 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
490 assertFalse(dpm.isAdminActive(admin1));
491 assertTrue(dpm.isAdminActive(admin2));
492 }
493
Makoto Onukif76b06a2015-09-22 15:03:44 -0700494 /**
495 * Test for:
496 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800497 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700498 */
499 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
500 // 1. Make sure the caller has proper permissions.
501 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
502
503 dpm.setActiveAdmin(admin1, /* replace =*/ false);
504 assertTrue(dpm.isAdminActive(admin1));
505
506 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100507 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
508 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700509 }
510
511 /**
512 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800513 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
514 * BIND_DEVICE_ADMIN.
515 */
516 public void testSetActiveAdmin_permissionCheck() throws Exception {
517 // 1. Make sure the caller has proper permissions.
518 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
519
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100520 assertExpectException(IllegalArgumentException.class,
521 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
522 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800523 assertFalse(dpm.isAdminActive(adminNoPerm));
524
525 // Change the target API level to MNC. Now it can be set as DA.
526 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
527 VERSION_CODES.M);
528 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
529 assertTrue(dpm.isAdminActive(adminNoPerm));
530
531 // TODO Test the "load from the file" case where DA will still be loaded even without
532 // BIND_DEVICE_ADMIN and target API is N.
533 }
534
535 /**
536 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700537 * {@link DevicePolicyManager#removeActiveAdmin}
538 */
539 public void testRemoveActiveAdmin_SecurityException() {
540 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
541
542 // Add admin.
543
544 dpm.setActiveAdmin(admin1, /* replace =*/ false);
545
546 assertTrue(dpm.isAdminActive(admin1));
547
548 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
549
550 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100551 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
552 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700553
554 // Try to remove active admin with a different caller userid should fail too, without
555 // having MANAGE_DEVICE_ADMINS.
556 mContext.callerPermissions.clear();
557
Makoto Onukid932f762015-09-29 16:53:38 -0700558 // Change the caller, and call into DPMS directly with a different user-id.
559
Makoto Onukif76b06a2015-09-22 15:03:44 -0700560 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100561 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
562 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700563 }
564
565 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800566 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
567 * (because we can't send the remove broadcast).
568 */
569 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
570 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
571
572 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
573
574 // Add admin.
575
576 dpm.setActiveAdmin(admin1, /* replace =*/ false);
577
578 assertTrue(dpm.isAdminActive(admin1));
579
580 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
581
582 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100583 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800584 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100585 assertExpectException(IllegalStateException.class,
586 /* messageRegex= */ "User must be running and unlocked",
587 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800588
589 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800590 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
591 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800592
593 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100594 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800595 .thenReturn(true);
596
597 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700598 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800599 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
600 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800601 }
602
603 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700604 * Test for:
605 * {@link DevicePolicyManager#removeActiveAdmin}
606 */
Makoto Onukid932f762015-09-29 16:53:38 -0700607 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700608 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
609
610 // Add admin1.
611
612 dpm.setActiveAdmin(admin1, /* replace =*/ false);
613
614 assertTrue(dpm.isAdminActive(admin1));
615 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
616
617 // Different user, but should work, because caller has proper permissions.
618 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700619
620 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700621 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700622
623 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700624 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800625 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
626 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700627
628 // TODO DO Still can't be removed in this case.
629 }
630
631 /**
632 * Test for:
633 * {@link DevicePolicyManager#removeActiveAdmin}
634 */
635 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
636 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
637 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
638
639 // Add admin1.
640
641 dpm.setActiveAdmin(admin1, /* replace =*/ false);
642
643 assertTrue(dpm.isAdminActive(admin1));
644 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
645
646 // Broadcast from saveSettingsLocked().
647 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
648 MockUtils.checkIntentAction(
649 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
650 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
651
652 // Remove. No permissions, but same user, so it'll work.
653 mContext.callerPermissions.clear();
654 dpm.removeActiveAdmin(admin1);
655
Makoto Onukif76b06a2015-09-22 15:03:44 -0700656 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
657 MockUtils.checkIntentAction(
658 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
659 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
660 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700661 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700662 eq(dpms.mHandler),
663 eq(Activity.RESULT_OK),
664 isNull(String.class),
665 isNull(Bundle.class));
666
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700667 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800668 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
669 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700670
671 // Again broadcast from saveSettingsLocked().
672 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
673 MockUtils.checkIntentAction(
674 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
675 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
676
677 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700678 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700679
Sudheer Shanka101c3532018-01-08 16:28:42 -0800680 public void testRemoveActiveAdmin_multipleAdminsInUser() {
681 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
682 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
683
684 // Add admin1.
685 dpm.setActiveAdmin(admin1, /* replace =*/ false);
686
687 assertTrue(dpm.isAdminActive(admin1));
688 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
689
690 // Add admin2.
691 dpm.setActiveAdmin(admin2, /* replace =*/ false);
692
693 assertTrue(dpm.isAdminActive(admin2));
694 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
695
696 // Broadcast from saveSettingsLocked().
697 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
698 MockUtils.checkIntentAction(
699 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
700 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
701
702 // Remove. No permissions, but same user, so it'll work.
703 mContext.callerPermissions.clear();
704 dpm.removeActiveAdmin(admin1);
705
706 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
707 MockUtils.checkIntentAction(
708 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
709 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
710 isNull(String.class),
711 any(BroadcastReceiver.class),
712 eq(dpms.mHandler),
713 eq(Activity.RESULT_OK),
714 isNull(String.class),
715 isNull(Bundle.class));
716
717 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
718 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800719 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800720 eq(DpmMockContext.CALLER_USER_HANDLE));
721
722 // Again broadcast from saveSettingsLocked().
723 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
724 MockUtils.checkIntentAction(
725 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
726 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
727 }
728
729 /**
730 * Test for:
731 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
732 */
733 public void testForceRemoveActiveAdmin() throws Exception {
734 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
735
736 // Add admin.
737 setupPackageInPackageManager(admin1.getPackageName(),
738 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
739 /* appId= */ 10138,
740 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
741 dpm.setActiveAdmin(admin1, /* replace =*/ false);
742 assertTrue(dpm.isAdminActive(admin1));
743
744 // Calling from a non-shell uid should fail with a SecurityException
745 mContext.binder.callingUid = 123456;
746 assertExpectException(SecurityException.class,
747 /* messageRegex =*/ "Non-shell user attempted to call",
748 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
749
750 mContext.binder.callingUid = Process.SHELL_UID;
751 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
752
753 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
754 // Verify
755 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
756 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
757 null, DpmMockContext.CALLER_USER_HANDLE);
758 }
759
Makoto Onukib643fb02015-09-22 15:03:44 -0700760 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000761 * Test for: @{link DevicePolicyManager#setActivePasswordState}
762 *
763 * Validates that when the password for a user changes, the notification broadcast intent
764 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
765 * addition to ones in the original user.
766 */
767 public void testSetActivePasswordState_sendToProfiles() throws Exception {
768 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
769
770 final int MANAGED_PROFILE_USER_ID = 78;
771 final int MANAGED_PROFILE_ADMIN_UID =
772 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
773
774 // Setup device owner.
775 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
776 mContext.packageName = admin1.getPackageName();
777 setupDeviceOwner();
778
779 // Add a managed profile belonging to the system user.
780 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
781
782 // Change the parent user's password.
783 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
784
785 // Both the device owner and the managed profile owner should receive this broadcast.
786 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
787 intent.setComponent(admin1);
788 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
789
790 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
791 MockUtils.checkIntent(intent),
792 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
793 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
794 MockUtils.checkIntent(intent),
795 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
796 }
797
798 /**
799 * Test for: @{link DevicePolicyManager#setActivePasswordState}
800 *
801 * Validates that when the password for a managed profile changes, the notification broadcast
802 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
803 * its parent.
804 */
805 public void testSetActivePasswordState_notSentToParent() throws Exception {
806 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
807
808 final int MANAGED_PROFILE_USER_ID = 78;
809 final int MANAGED_PROFILE_ADMIN_UID =
810 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
811
812 // Setup device owner.
813 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
814 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100815 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000816 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
817 setupDeviceOwner();
818
819 // Add a managed profile belonging to the system user.
820 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
821
822 // Change the profile's password.
823 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
824
825 // Both the device owner and the managed profile owner should receive this broadcast.
826 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
827 intent.setComponent(admin1);
828 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
829
830 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
831 MockUtils.checkIntent(intent),
832 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
833 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
834 MockUtils.checkIntent(intent),
835 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
836 }
837 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000838 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700839 */
840 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000841 setDeviceOwner();
842
843 // Try to set a profile owner on the same user, which should fail.
844 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
845 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100846 assertExpectException(IllegalStateException.class,
847 /* messageRegex= */ "already has a device owner",
848 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000849
850 // DO admin can't be deactivated.
851 dpm.removeActiveAdmin(admin1);
852 assertTrue(dpm.isAdminActive(admin1));
853
854 // TODO Test getDeviceOwnerName() too. To do so, we need to change
855 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
856 }
857
858 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700859 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800860 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700861 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
862 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
863
Makoto Onukid932f762015-09-29 16:53:38 -0700864 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
866
Makoto Onukid932f762015-09-29 16:53:38 -0700867 // Make sure admin1 is installed on system user.
868 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700869
Makoto Onukic8a5a552015-11-19 14:29:12 -0800870 // Check various get APIs.
871 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
872
Makoto Onukib643fb02015-09-22 15:03:44 -0700873 // DO needs to be an DA.
874 dpm.setActiveAdmin(admin1, /* replace =*/ false);
875
876 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700877 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700878
Makoto Onukic8a5a552015-11-19 14:29:12 -0800879 // getDeviceOwnerComponent should return the admin1 component.
880 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
881 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
882
883 // Check various get APIs.
884 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
885
886 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
887 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
888 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
889 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
890
891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
892
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000893 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100894 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000895 eq(admin1.getPackageName()));
896
Makoto Onukib643fb02015-09-22 15:03:44 -0700897 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100898 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700899 eq(UserHandle.USER_SYSTEM), eq(false));
900
901 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
902 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
903 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
904
Makoto Onukic8a5a552015-11-19 14:29:12 -0800905 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 }
907
Makoto Onukic8a5a552015-11-19 14:29:12 -0800908 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
909 final int origCallingUser = mContext.binder.callingUid;
910 final List origPermissions = new ArrayList(mContext.callerPermissions);
911 mContext.callerPermissions.clear();
912
913 mContext.callerPermissions.add(permission.MANAGE_USERS);
914
915 mContext.binder.callingUid = Process.SYSTEM_UID;
916
917 // TODO Test getDeviceOwnerName() too. To do so, we need to change
918 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
919 if (hasDeviceOwner) {
920 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
921 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
922 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
923
924 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
925 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
926 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
927 } else {
928 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
929 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
930 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
931
932 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
933 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
934 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
935 }
936
937 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
938 if (hasDeviceOwner) {
939 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
940 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
941 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
942
943 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
944 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
945 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
946 } else {
947 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
948 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
949 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
950
951 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
952 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
953 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
954 }
955
956 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
957 // Still with MANAGE_USERS.
958 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
959 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
960 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
961
962 if (hasDeviceOwner) {
963 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
964 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
965 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
966 } else {
967 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
968 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
969 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
970 }
971
972 mContext.binder.callingUid = Process.SYSTEM_UID;
973 mContext.callerPermissions.remove(permission.MANAGE_USERS);
974 // System can still call "OnAnyUser" without MANAGE_USERS.
975 if (hasDeviceOwner) {
976 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
977 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
978 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
979
980 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
981 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
982 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
983 } else {
984 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
985 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
986 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
987
988 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
989 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
990 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
991 }
992
993 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
994 // Still no MANAGE_USERS.
995 if (hasDeviceOwner) {
996 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
997 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
998 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
999 } else {
1000 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1001 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1002 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1003 }
1004
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001005 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1006 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1007 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1008 dpm::getDeviceOwnerComponentOnAnyUser);
1009 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1010 dpm::getDeviceOwnerUserId);
1011 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1012 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001013
1014 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1015 // Still no MANAGE_USERS.
1016 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1017 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1018 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1019
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001020 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1021 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1022 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1023 dpm::getDeviceOwnerComponentOnAnyUser);
1024 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1025 dpm::getDeviceOwnerUserId);
1026 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1027 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001028
1029 // Restore.
1030 mContext.binder.callingUid = origCallingUser;
1031 mContext.callerPermissions.addAll(origPermissions);
1032 }
1033
1034
Makoto Onukib643fb02015-09-22 15:03:44 -07001035 /**
1036 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1037 */
1038 public void testSetDeviceOwner_noSuchPackage() {
1039 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001040 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001041 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1042 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1043
1044 // Call from a process on the system user.
1045 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1046
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001047 assertExpectException(IllegalArgumentException.class,
1048 /* messageRegex= */ "Invalid component",
1049 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001050 }
1051
1052 public void testSetDeviceOwner_failures() throws Exception {
1053 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1054 }
1055
Makoto Onukia52562c2015-10-01 16:12:31 -07001056 public void testClearDeviceOwner() throws Exception {
1057 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001058 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001059 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1060 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1061
1062 // Set admin1 as a DA to the secondary user.
1063 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1064
1065 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1066
1067 // Set admin 1 as the DO to the system user.
1068
1069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1070 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1071 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1072 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1073
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001074 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001075 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001076 eq(admin1.getPackageName()));
1077
Makoto Onukic8a5a552015-11-19 14:29:12 -08001078 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001079
Makoto Onuki90b89652016-01-28 14:44:18 -08001080 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001081 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001082 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001083
1084 assertTrue(dpm.isAdminActive(admin1));
1085 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1086
Makoto Onukia52562c2015-10-01 16:12:31 -07001087 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001088 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001089
1090 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1092 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001093
1094 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001095 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001096 assertExpectException(IllegalStateException.class,
1097 /* messageRegex= */ "User must be running and unlocked",
1098 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001099
Pavel Grafov75c0a892017-05-18 17:28:27 +01001100 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1101 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001102 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1103
1104 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001105 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001106
Pavel Grafov75c0a892017-05-18 17:28:27 +01001107 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001108 eq(false),
1109 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1110
Pavel Grafov75c0a892017-05-18 17:28:27 +01001111 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001112 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001113 eq(null),
1114 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001115
Sudheer Shanka101c3532018-01-08 16:28:42 -08001116 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1117 null, UserHandle.USER_SYSTEM);
1118
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001119 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001120
1121 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1122 // and once for clearing it.
1123 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1124 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1125 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001126 // TODO Check other calls.
1127 }
1128
1129 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1130 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001131 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001132 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1133 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1134
1135 // Set admin1 as a DA to the secondary user.
1136 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1137
1138 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1139
1140 // Set admin 1 as the DO to the system user.
1141
1142 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1143 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1144 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1145 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1146
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001147 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001148 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001149 eq(admin1.getPackageName()));
1150
Makoto Onukic8a5a552015-11-19 14:29:12 -08001151 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001152
1153 // Now call clear from the secondary user, which should throw.
1154 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1155
1156 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001157 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001158 eq(admin1.getPackageName()),
1159 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001160 assertExpectException(SecurityException.class,
1161 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1162 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001163
Makoto Onukic8a5a552015-11-19 14:29:12 -08001164 // DO shouldn't be removed.
1165 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001166 }
1167
Makoto Onukib643fb02015-09-22 15:03:44 -07001168 public void testSetProfileOwner() throws Exception {
1169 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001170
Makoto Onuki90b89652016-01-28 14:44:18 -08001171 // PO admin can't be deactivated.
1172 dpm.removeActiveAdmin(admin1);
1173 assertTrue(dpm.isAdminActive(admin1));
1174
Makoto Onuki803d6752015-10-30 12:58:39 -07001175 // Try setting DO on the same user, which should fail.
1176 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001177 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1178 runAsCaller(mServiceContext, dpms, dpm -> {
1179 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001180 assertExpectException(IllegalStateException.class,
1181 /* messageRegex= */ "already has a profile owner",
1182 () -> dpm.setDeviceOwner(admin2, "owner-name",
1183 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001184 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001185 }
1186
Makoto Onuki90b89652016-01-28 14:44:18 -08001187 public void testClearProfileOwner() throws Exception {
1188 setAsProfileOwner(admin1);
1189
1190 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1191
1192 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1193 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1194
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001195 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001196 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001197 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001198 assertExpectException(IllegalStateException.class,
1199 /* messageRegex= */ "User must be running and unlocked",
1200 () -> dpm.clearProfileOwner(admin1));
1201
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001202 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001203 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001204 dpm.clearProfileOwner(admin1);
1205
1206 // Check
1207 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001208 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001209 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1210 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001211 }
1212
Makoto Onukib643fb02015-09-22 15:03:44 -07001213 public void testSetProfileOwner_failures() throws Exception {
1214 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1215 }
1216
Makoto Onukia52562c2015-10-01 16:12:31 -07001217 public void testGetDeviceOwnerAdminLocked() throws Exception {
1218 checkDeviceOwnerWithMultipleDeviceAdmins();
1219 }
1220
1221 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1222 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1223 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1224 // make sure it gets the right component from the right user.
1225
1226 final int ANOTHER_USER_ID = 100;
1227 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1228
Pavel Grafov75c0a892017-05-18 17:28:27 +01001229 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001230
1231 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001232 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001233 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1234 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1235
1236 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1237
Pavel Grafov75c0a892017-05-18 17:28:27 +01001238 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001239
Makoto Onukia52562c2015-10-01 16:12:31 -07001240 // Make sure the admin packge is installed to each user.
1241 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1242 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1243
1244 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1245 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1246
1247 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1248
1249
1250 // Set active admins to the users.
1251 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1252 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1253
1254 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1255 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1256
1257 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1258
1259 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001260 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001261 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1262
Makoto Onukic8a5a552015-11-19 14:29:12 -08001263 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001264
1265 // Then check getDeviceOwnerAdminLocked().
1266 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1267 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1268 }
1269
1270 /**
1271 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001272 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1273 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001274 *
1275 * We didn't use to persist the DO component class name, but now we do, and the above method
1276 * finds the right component from a package name upon migration.
1277 */
1278 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001279 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001280 checkDeviceOwnerWithMultipleDeviceAdmins();
1281
1282 // Overwrite the device owner setting and clears the clas name.
1283 dpms.mOwners.setDeviceOwner(
1284 new ComponentName(admin2.getPackageName(), ""),
1285 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1286 dpms.mOwners.writeDeviceOwner();
1287
1288 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001289 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001290
1291 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001292 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001293 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001294 initializeDpms();
1295
1296 // Now the DO component name is a full name.
1297 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1298 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001299 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001300 }
1301
Makoto Onukib643fb02015-09-22 15:03:44 -07001302 public void testSetGetApplicationRestriction() {
1303 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001304 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001305
1306 {
1307 Bundle rest = new Bundle();
1308 rest.putString("KEY_STRING", "Foo1");
1309 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1310 }
1311
1312 {
1313 Bundle rest = new Bundle();
1314 rest.putString("KEY_STRING", "Foo2");
1315 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1316 }
1317
1318 {
1319 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1320 assertNotNull(returned);
1321 assertEquals(returned.size(), 1);
1322 assertEquals(returned.get("KEY_STRING"), "Foo1");
1323 }
1324
1325 {
1326 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1327 assertNotNull(returned);
1328 assertEquals(returned.size(), 1);
1329 assertEquals(returned.get("KEY_STRING"), "Foo2");
1330 }
1331
1332 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1333 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1334 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001335
Edman Anjosf9946772016-11-28 16:35:15 +01001336 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001337 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1338 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001339 *
1340 * @param packageName the name of the package to be setup
1341 * @param appId the application ID to be given to the package
1342 * @return the UID of the package as known by the mock package manager
1343 */
1344 private int setupPackageInPackageManager(final String packageName, final int appId)
1345 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001346 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001347 ApplicationInfo.FLAG_HAS_CODE);
1348 }
1349
1350 /**
1351 * Setup a package in the package manager mock. Useful for faking installed applications.
1352 *
1353 * @param packageName the name of the package to be setup
1354 * @param userId the user id where the package will be "installed"
1355 * @param appId the application ID to be given to the package
1356 * @param flags flags to set in the ApplicationInfo for this package
1357 * @return the UID of the package as known by the mock package manager
1358 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001359 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1360 int flags) throws Exception {
1361 final int uid = UserHandle.getUid(userId, appId);
1362 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001363 final PackageInfo pi = new PackageInfo();
1364 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001365 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001366 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001367 eq(packageName),
1368 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001369 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001370 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001371 eq(packageName),
1372 anyInt(),
1373 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001374 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001375 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001376 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001377 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001378 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001379 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001380 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001381 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001383 return uid;
1384 }
1385
Robin Lee7f5c91c2017-02-08 21:27:02 +00001386 public void testCertificateDisclosure() throws Exception {
1387 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1388 final UserHandle user = UserHandle.of(userId);
1389
1390 mContext.applicationInfo = new ApplicationInfo();
1391 mContext.callerPermissions.add(permission.MANAGE_USERS);
1392 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001393 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001394 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1395
Robin Leeabaa0692017-02-20 20:54:22 +00001396 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1397 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001398
1399 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1400 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1401
1402 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001403 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001404 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001405 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001406 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001407 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001408 .cancelAsUser(anyString(), anyInt(), eq(user));
1409
1410 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001411 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001412 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001413 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1414 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001415 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001416 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001417 .notifyAsUser(anyString(), anyInt(), argThat(
1418 new BaseMatcher<Notification>() {
1419 @Override
1420 public boolean matches(Object item) {
1421 final Notification noti = (Notification) item;
1422 return TEST_STRING.equals(
1423 noti.extras.getString(Notification.EXTRA_TITLE));
1424 }
1425 @Override
1426 public void describeTo(Description description) {
1427 description.appendText(
1428 "Notification{title=\"" + TEST_STRING + "\"}");
1429 }
1430 }), eq(user));
1431 }
1432
Edman Anjosf9946772016-11-28 16:35:15 +01001433 /**
1434 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1435 * privileges can acually be exercised by a delegate are not covered here.
1436 */
1437 public void testDelegation() throws Exception {
1438 setAsProfileOwner(admin1);
1439
1440 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1441
1442 // Given two packages
1443 final String CERT_DELEGATE = "com.delegate.certs";
1444 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1445 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1446 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1447 20989);
1448
1449 // On delegation
1450 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1451 mContext.packageName = admin1.getPackageName();
1452 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1453 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1454
1455 // DPMS correctly stores and retrieves the delegates
1456 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1457 assertEquals(2, policy.mDelegationMap.size());
1458 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1459 DELEGATION_CERT_INSTALL);
1460 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1461 DELEGATION_CERT_INSTALL);
1462 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1463 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1464 DELEGATION_APP_RESTRICTIONS);
1465 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1466 DELEGATION_APP_RESTRICTIONS);
1467 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1468
1469 // On calling install certificate APIs from an unauthorized process
1470 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1471 mContext.packageName = RESTRICTIONS_DELEGATE;
1472
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001473 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1474 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001475
1476 // On calling install certificate APIs from an authorized process
1477 mContext.binder.callingUid = CERT_DELEGATE_UID;
1478 mContext.packageName = CERT_DELEGATE;
1479
1480 // DPMS executes without a SecurityException
1481 try {
1482 dpm.installCaCert(null, null);
1483 } catch (SecurityException unexpected) {
1484 fail("Threw SecurityException on authorized access");
1485 } catch (NullPointerException expected) {
1486 }
1487
1488 // On removing a delegate
1489 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1490 mContext.packageName = admin1.getPackageName();
1491 dpm.setCertInstallerPackage(admin1, null);
1492
1493 // DPMS does not allow access to ex-delegate
1494 mContext.binder.callingUid = CERT_DELEGATE_UID;
1495 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001496 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1497 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001498
1499 // But still allows access to other existing delegates
1500 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1501 mContext.packageName = RESTRICTIONS_DELEGATE;
1502 try {
1503 dpm.getApplicationRestrictions(null, "pkg");
1504 } catch (SecurityException expected) {
1505 fail("Threw SecurityException on authorized access");
1506 }
1507 }
1508
Esteban Talaverabf60f722015-12-10 16:26:44 +00001509 public void testApplicationRestrictionsManagingApp() throws Exception {
1510 setAsProfileOwner(admin1);
1511
Rubin Xued1928a2016-02-11 17:23:06 +00001512 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001513 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001514 final String nonDelegateExceptionMessageRegex =
1515 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001516 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001517 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1518 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001519
Esteban Talaverabf60f722015-12-10 16:26:44 +00001520 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1521 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001522 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1523 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001524 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001525 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001526 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001527 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1528 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001529
1530 // Check via the profile owner that no restrictions were set.
1531 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001532 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001533 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1534
Rubin Xued1928a2016-02-11 17:23:06 +00001535 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001536 assertExpectException(PackageManager.NameNotFoundException.class,
1537 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1538 () -> dpm.setApplicationRestrictionsManagingPackage(
1539 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001540
Esteban Talaverabf60f722015-12-10 16:26:44 +00001541 // Let appRestrictionsManagerPackage manage app restrictions
1542 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1543 assertEquals(appRestrictionsManagerPackage,
1544 dpm.getApplicationRestrictionsManagingPackage(admin1));
1545
1546 // Now that package should be able to set and retrieve app restrictions.
1547 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001548 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001549 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1550 dpm.setApplicationRestrictions(null, "pkg1", rest);
1551 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1552 assertEquals(1, returned.size(), 1);
1553 assertEquals("Foo1", returned.get("KEY_STRING"));
1554
1555 // The same app running on a separate user shouldn't be able to manage app restrictions.
1556 mContext.binder.callingUid = UserHandle.getUid(
1557 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1558 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001559 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1560 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001561
1562 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1563 // too.
1564 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001565 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001566 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1567 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1568 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1569
1570 // Removing the ability for the package to manage app restrictions.
1571 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1572 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1573 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001574 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001575 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001576 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1577 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001578 }
1579
Makoto Onukia4f11972015-10-01 13:19:58 -07001580 public void testSetUserRestriction_asDo() throws Exception {
1581 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001582 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001583 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1584 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1585
1586 // First, set DO.
1587
1588 // Call from a process on the system user.
1589 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1590
1591 // Make sure admin1 is installed on system user.
1592 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001593
1594 // Call.
1595 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001596 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001597 UserHandle.USER_SYSTEM));
1598
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001599 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001600 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001601 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001602 DpmTestUtils.assertRestrictions(
1603 DpmTestUtils.newRestrictions(defaultRestrictions),
1604 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1605 );
1606 DpmTestUtils.assertRestrictions(
1607 DpmTestUtils.newRestrictions(defaultRestrictions),
1608 dpm.getUserRestrictions(admin1)
1609 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001610 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001611 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001612 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001613 eq(true) /* isDeviceOwner */,
1614 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001615 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001616 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001617
1618 for (String restriction : defaultRestrictions) {
1619 dpm.clearUserRestriction(admin1, restriction);
1620 }
1621
Esteban Talavera548a04b2016-12-20 15:22:30 +00001622 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001623 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624
1625 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001627 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001628 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1629 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001630 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001631
Makoto Onukia4f11972015-10-01 13:19:58 -07001632 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001633 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001634 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001635 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1636 UserManager.DISALLOW_ADD_USER),
1637 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001639
Makoto Onuki068c54a2015-10-13 14:34:03 -07001640 DpmTestUtils.assertRestrictions(
1641 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001643 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1644 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001645 DpmTestUtils.assertRestrictions(
1646 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001648 dpm.getUserRestrictions(admin1)
1649 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001650
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001651 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001652 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 eq(UserHandle.USER_SYSTEM),
1654 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001655 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001656 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001657
Makoto Onuki068c54a2015-10-13 14:34:03 -07001658 DpmTestUtils.assertRestrictions(
1659 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1660 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1661 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001662 DpmTestUtils.assertRestrictions(
1663 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1664 dpm.getUserRestrictions(admin1)
1665 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001666
1667 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001668 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 eq(UserHandle.USER_SYSTEM),
1670 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001671 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001673
Esteban Talavera548a04b2016-12-20 15:22:30 +00001674 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001675
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001676 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1677 // DO sets them, the scope is global.
1678 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001679 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001680 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001681 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001682 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001683 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001684 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1685 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001686 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001687
1688 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1689 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001690 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691
1692 // More tests.
1693 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001694 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001695 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001696 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1697 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001698 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699
1700 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001701 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001703 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001704 UserManager.DISALLOW_ADD_USER),
1705 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001706 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707
1708 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 eq(UserHandle.USER_SYSTEM),
1711 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001712 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001713 UserManager.DISALLOW_ADD_USER),
1714 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001715 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001716 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717
Eric Sandnessca5969d2018-08-10 13:28:46 +01001718 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1719 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1720 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721
Eric Sandnessca5969d2018-08-10 13:28:46 +01001722 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1723 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001724
Eric Sandnessca5969d2018-08-10 13:28:46 +01001725 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1726 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1727 () -> dpm.setCameraDisabled(admin1, true));
1728 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1729
1730 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1731 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1732 () -> dpm.setKeyguardDisabledFeatures(admin1,
1733 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1734 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1735
1736 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1737 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1738 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1739 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1740
1741 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1742 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1743 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1744 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001745 }
1746
1747 public void testSetUserRestriction_asPo() {
1748 setAsProfileOwner(admin1);
1749
Makoto Onuki068c54a2015-10-13 14:34:03 -07001750 DpmTestUtils.assertRestrictions(
1751 DpmTestUtils.newRestrictions(),
1752 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1753 .ensureUserRestrictions()
1754 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001755
1756 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001757 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001758 eq(DpmMockContext.CALLER_USER_HANDLE),
1759 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001760 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001761 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001762
Makoto Onukia4f11972015-10-01 13:19:58 -07001763 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001764 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765 eq(DpmMockContext.CALLER_USER_HANDLE),
1766 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1767 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001768 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001770
Makoto Onuki068c54a2015-10-13 14:34:03 -07001771 DpmTestUtils.assertRestrictions(
1772 DpmTestUtils.newRestrictions(
1773 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1774 UserManager.DISALLOW_OUTGOING_CALLS
1775 ),
1776 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1777 .ensureUserRestrictions()
1778 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001779 DpmTestUtils.assertRestrictions(
1780 DpmTestUtils.newRestrictions(
1781 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1782 UserManager.DISALLOW_OUTGOING_CALLS
1783 ),
1784 dpm.getUserRestrictions(admin1)
1785 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001786
1787 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001788 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 eq(DpmMockContext.CALLER_USER_HANDLE),
1790 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001791 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001792 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001793
1794 DpmTestUtils.assertRestrictions(
1795 DpmTestUtils.newRestrictions(
1796 UserManager.DISALLOW_OUTGOING_CALLS
1797 ),
1798 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1799 .ensureUserRestrictions()
1800 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001801 DpmTestUtils.assertRestrictions(
1802 DpmTestUtils.newRestrictions(
1803 UserManager.DISALLOW_OUTGOING_CALLS
1804 ),
1805 dpm.getUserRestrictions(admin1)
1806 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001807
1808 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810 eq(DpmMockContext.CALLER_USER_HANDLE),
1811 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001812 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001814
Makoto Onuki068c54a2015-10-13 14:34:03 -07001815 DpmTestUtils.assertRestrictions(
1816 DpmTestUtils.newRestrictions(),
1817 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1818 .ensureUserRestrictions()
1819 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001820 DpmTestUtils.assertRestrictions(
1821 DpmTestUtils.newRestrictions(),
1822 dpm.getUserRestrictions(admin1)
1823 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001824
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001825 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1826 // though when DO sets them they'll be applied globally.
1827 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001828 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001829 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001830 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 eq(DpmMockContext.CALLER_USER_HANDLE),
1832 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1833 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001834 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001835 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836
1837 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001838 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001839 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001840 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001841 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001842 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001843 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844
Makoto Onukia4f11972015-10-01 13:19:58 -07001845 // TODO Make sure restrictions are written to the file.
1846 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001847
Esteban Talavera548a04b2016-12-20 15:22:30 +00001848
1849 public void testDefaultEnabledUserRestrictions() throws Exception {
1850 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1851 mContext.callerPermissions.add(permission.MANAGE_USERS);
1852 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1853 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1854
1855 // First, set DO.
1856
1857 // Call from a process on the system user.
1858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1859
1860 // Make sure admin1 is installed on system user.
1861 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1862
1863 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1864 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1865 UserHandle.USER_SYSTEM));
1866
1867 // Check that the user restrictions that are enabled by default are set. Then unset them.
1868 String[] defaultRestrictions = UserRestrictionsUtils
1869 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1870 assertTrue(defaultRestrictions.length > 0);
1871 DpmTestUtils.assertRestrictions(
1872 DpmTestUtils.newRestrictions(defaultRestrictions),
1873 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1874 );
1875 DpmTestUtils.assertRestrictions(
1876 DpmTestUtils.newRestrictions(defaultRestrictions),
1877 dpm.getUserRestrictions(admin1)
1878 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001879 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001880 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001881 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001882 eq(true) /* isDeviceOwner */,
1883 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001884 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001885 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001886
1887 for (String restriction : defaultRestrictions) {
1888 dpm.clearUserRestriction(admin1, restriction);
1889 }
1890
1891 assertNoDeviceOwnerRestrictions();
1892
1893 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001894 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001895 initializeDpms();
1896 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1897 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1898
1899 assertNoDeviceOwnerRestrictions();
1900
1901 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1902 // is set as it wasn't enabled during setDeviceOwner.
1903 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1904 assertFalse(UserRestrictionsUtils
1905 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1906 UserRestrictionsUtils
1907 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1908 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001909 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001910 initializeDpms();
1911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1912 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1913
1914 DpmTestUtils.assertRestrictions(
1915 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1916 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1917 );
1918 DpmTestUtils.assertRestrictions(
1919 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1920 dpm.getUserRestrictions(admin1)
1921 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001922 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001923 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001924 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001925 eq(true) /* isDeviceOwner */,
1926 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001927 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001928 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001929
1930 // Remove the restriction.
1931 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1932
1933 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1934 initializeDpms();
1935 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1936 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1937 assertNoDeviceOwnerRestrictions();
1938 } finally {
1939 UserRestrictionsUtils
1940 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1941 }
1942 }
1943
1944 private void assertNoDeviceOwnerRestrictions() {
1945 DpmTestUtils.assertRestrictions(
1946 DpmTestUtils.newRestrictions(),
1947 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1948 );
1949 DpmTestUtils.assertRestrictions(
1950 DpmTestUtils.newRestrictions(),
1951 dpm.getUserRestrictions(admin1)
1952 );
1953 }
1954
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001955 public void testGetMacAddress() throws Exception {
1956 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1957 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1958 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1959
1960 // In this test, change the caller user to "system".
1961 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1962
1963 // Make sure admin1 is installed on system user.
1964 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1965
1966 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001967 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1968 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001969
1970 // DO needs to be an DA.
1971 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1972 assertTrue(dpm.isAdminActive(admin1));
1973
1974 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001975 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1976 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001977
1978 // Test 3. Caller has PO, but not DO.
1979 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001980 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1981 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001982
1983 // Remove PO.
1984 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001985 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001986 // Test 4, Caller is DO now.
1987 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1988
1989 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001990 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001991
1992 // 4-2. Returns WifiInfo, but with the default MAC.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001993 when(getServices().wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001994 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001995
1996 // 4-3. With a real MAC address.
1997 final WifiInfo wi = new WifiInfo();
1998 wi.setMacAddress("11:22:33:44:55:66");
Pavel Grafov75c0a892017-05-18 17:28:27 +01001999 when(getServices().wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002000 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002001 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002002
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002003 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002004 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2005 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2006
2007 // In this test, change the caller user to "system".
2008 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2009
2010 // Make sure admin1 is installed on system user.
2011 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2012
2013 // Set admin1 as DA.
2014 dpm.setActiveAdmin(admin1, false);
2015 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002016 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2017 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002018
2019 // Set admin1 as PO.
2020 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
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 // Remove PO and add DO.
2025 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002026 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002027 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2028
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002029 // admin1 is DO.
2030 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002031 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002032 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002033 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2034 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002035
2036 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002037 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002038 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002039 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2040 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002041
2042 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002043 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002044 dpm.reboot(admin1);
2045 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002046
2047 public void testSetGetSupportText() {
2048 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2049 dpm.setActiveAdmin(admin1, true);
2050 dpm.setActiveAdmin(admin2, true);
2051 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2052
2053 // Null default support messages.
2054 {
2055 assertNull(dpm.getLongSupportMessage(admin1));
2056 assertNull(dpm.getShortSupportMessage(admin1));
2057 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2058 assertNull(dpm.getShortSupportMessageForUser(admin1,
2059 DpmMockContext.CALLER_USER_HANDLE));
2060 assertNull(dpm.getLongSupportMessageForUser(admin1,
2061 DpmMockContext.CALLER_USER_HANDLE));
2062 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2063 }
2064
2065 // Only system can call the per user versions.
2066 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002067 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2068 () -> dpm.getShortSupportMessageForUser(admin1,
2069 DpmMockContext.CALLER_USER_HANDLE));
2070 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2071 () -> dpm.getLongSupportMessageForUser(admin1,
2072 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002073 }
2074
2075 // Can't set message for admin in another uid.
2076 {
2077 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002078 assertExpectException(SecurityException.class,
2079 /* messageRegex= */ "is not owned by uid",
2080 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002081 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2082 }
2083
2084 // Set/Get short returns what it sets and other admins text isn't changed.
2085 {
2086 final String supportText = "Some text to test with.";
2087 dpm.setShortSupportMessage(admin1, supportText);
2088 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2089 assertNull(dpm.getLongSupportMessage(admin1));
2090 assertNull(dpm.getShortSupportMessage(admin2));
2091
2092 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2093 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2094 DpmMockContext.CALLER_USER_HANDLE));
2095 assertNull(dpm.getShortSupportMessageForUser(admin2,
2096 DpmMockContext.CALLER_USER_HANDLE));
2097 assertNull(dpm.getLongSupportMessageForUser(admin1,
2098 DpmMockContext.CALLER_USER_HANDLE));
2099 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2100
2101 dpm.setShortSupportMessage(admin1, null);
2102 assertNull(dpm.getShortSupportMessage(admin1));
2103 }
2104
2105 // Set/Get long returns what it sets and other admins text isn't changed.
2106 {
2107 final String supportText = "Some text to test with.\nWith more text.";
2108 dpm.setLongSupportMessage(admin1, supportText);
2109 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2110 assertNull(dpm.getShortSupportMessage(admin1));
2111 assertNull(dpm.getLongSupportMessage(admin2));
2112
2113 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2114 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2115 DpmMockContext.CALLER_USER_HANDLE));
2116 assertNull(dpm.getLongSupportMessageForUser(admin2,
2117 DpmMockContext.CALLER_USER_HANDLE));
2118 assertNull(dpm.getShortSupportMessageForUser(admin1,
2119 DpmMockContext.CALLER_USER_HANDLE));
2120 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2121
2122 dpm.setLongSupportMessage(admin1, null);
2123 assertNull(dpm.getLongSupportMessage(admin1));
2124 }
2125 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002126
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002127 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002128 setAsProfileOwner(admin1);
2129
2130 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002131 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002132
2133 // Setup
2134 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2135 final String package1 = "com.example.one";
2136 final String package2 = "com.example.two";
2137 pkgsToRestrict.add(package1);
2138 pkgsToRestrict.add(package2);
2139 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2140 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002141 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002142
2143 // Verify
2144 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002145 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002146 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2147 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2148 eq(DpmMockContext.CALLER_USER_HANDLE));
2149
2150 // Setup
2151 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002152 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002153
2154 // Verify
2155 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002156 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002157 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2158 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2159 eq(DpmMockContext.CALLER_USER_HANDLE));
2160 }
2161
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002162 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002163 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2164 dpm.setActiveAdmin(admin1, true);
2165 assertTrue(dpm.isAdminActive(admin1));
2166 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2167
2168 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002169 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002170 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002171 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002172 }
2173
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002174 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002175 setAsProfileOwner(admin1);
2176
2177 // Setup
2178 final ArrayList<String> emptyList = new ArrayList<>();
2179 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2180 final String package1 = "com.example.one";
2181 final String package2 = "com.example.two";
2182 final String package3 = "com.example.three";
2183 pkgsToRestrict.add(package1);
2184 pkgsToRestrict.add(package2);
2185 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2186 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002187 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002188
2189 // Verify
2190 assertEquals(emptyList, excludedPkgs);
2191 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2192 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002193 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002194 DpmMockContext.CALLER_USER_HANDLE));
2195 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002196 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002197 DpmMockContext.CALLER_USER_HANDLE));
2198 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002199 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002200 DpmMockContext.CALLER_USER_HANDLE));
2201 }
2202
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002203 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002204 setAsProfileOwner(admin1);
2205 assertExpectException(SecurityException.class,
2206 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002207 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002208 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2209 dpm.clearProfileOwner(admin1);
2210
2211 setDeviceOwner();
2212 assertExpectException(SecurityException.class,
2213 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002214 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002215 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2216 clearDeviceOwner();
2217 }
2218
phweiss73145f42017-01-17 19:06:38 +01002219 public void testCreateAdminSupportIntent() throws Exception {
2220 // Setup device owner.
2221 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2222 setupDeviceOwner();
2223
2224 // Nonexisting permission returns null
2225 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2226 assertNull(intent);
2227
2228 // Existing permission that is not set returns null
2229 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2230 assertNull(intent);
2231
2232 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002233 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002234 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2235 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2236 .thenReturn(true);
2237 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2238 assertNull(intent);
2239
2240 // Permission that is set by device owner returns correct intent
Pavel Grafov75c0a892017-05-18 17:28:27 +01002241 when(getServices().userManager.getUserRestrictionSource(
phweiss73145f42017-01-17 19:06:38 +01002242 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2243 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2244 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2245 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2246 assertNotNull(intent);
2247 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2248 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2249 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002250 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002251 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2252 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2253
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002254 // Try with POLICY_DISABLE_CAMERA, POLICY_DISABLE_SCREEN_CAPTURE and
2255 // POLICY_MANDATORY_BACKUPS, which are not user restrictions
phweiss73145f42017-01-17 19:06:38 +01002256
2257 // Camera is not disabled
2258 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2259 assertNull(intent);
2260
2261 // Camera is disabled
2262 dpm.setCameraDisabled(admin1, true);
2263 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2264 assertNotNull(intent);
2265 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2266 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2267
2268 // Screen capture is not disabled
2269 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2270 assertNull(intent);
2271
2272 // Screen capture is disabled
2273 dpm.setScreenCaptureDisabled(admin1, true);
2274 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2275 assertNotNull(intent);
2276 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2277 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2278
Lenka Trochtova56681f72018-03-09 15:47:50 +01002279 // Make the backup transport selection succeed
2280 doAnswer(new Answer<Void>() {
2281 @Override
2282 public Void answer(InvocationOnMock invocation) throws Throwable {
2283 ISelectBackupTransportCallback callback =
2284 (ISelectBackupTransportCallback) invocation.getArguments()[1];
2285 if (callback != null) {
2286 callback.onSuccess("");
2287 }
2288 return null;
2289 }
2290 }).when(getServices().ibackupManager).selectBackupTransportAsync(
2291 any(ComponentName.class), any(ISelectBackupTransportCallback.class));
2292
2293
Lenka Trochtova16a91c02018-01-17 11:03:30 +01002294 // Backups are not mandatory
2295 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2296 assertNull(intent);
2297
2298 // Backups are mandatory
2299 ComponentName transportComponent = ComponentName.unflattenFromString(
2300 "android/com.android.internal.backup.LocalTransport");
2301 dpm.setMandatoryBackupTransport(admin1, transportComponent);
2302 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_MANDATORY_BACKUPS);
2303 assertNotNull(intent);
2304 assertEquals(DevicePolicyManager.POLICY_MANDATORY_BACKUPS,
2305 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2306
phweiss73145f42017-01-17 19:06:38 +01002307 // Same checks for different user
2308 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2309 // Camera should be disabled by device owner
2310 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2311 assertNotNull(intent);
2312 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2313 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2314 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2315 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2316 // ScreenCapture should not be disabled by device owner
2317 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2318 assertNull(intent);
2319 }
2320
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002321 /**
2322 * Test for:
2323 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002324 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002325 * {@link DevicePolicyManager#isAffiliatedUser}
2326 */
2327 public void testUserAffiliation() throws Exception {
2328 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2329 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2330 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2331
2332 // Check that the system user is unaffiliated.
2333 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2334 assertFalse(dpm.isAffiliatedUser());
2335
2336 // Set a device owner on the system user. Check that the system user becomes affiliated.
2337 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2338 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2339 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2340 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002341 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002342
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002343 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002344 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2345 setAsProfileOwner(admin2);
2346 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002347 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002348
2349 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2350 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002351 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002352 userAffiliationIds.add("red");
2353 userAffiliationIds.add("green");
2354 userAffiliationIds.add("blue");
2355 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002356 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002357 assertFalse(dpm.isAffiliatedUser());
2358
2359 // Have the device owner specify a set of affiliation ids that do not intersect with those
2360 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002361 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002362 deviceAffiliationIds.add("cyan");
2363 deviceAffiliationIds.add("yellow");
2364 deviceAffiliationIds.add("magenta");
2365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2366 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002367 MoreAsserts.assertContentsInAnyOrder(
2368 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002369 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2370 assertFalse(dpm.isAffiliatedUser());
2371
2372 // Have the profile owner specify a set of affiliation ids that intersect with those
2373 // specified by the device owner. Check that the test user becomes affiliated.
2374 userAffiliationIds.add("yellow");
2375 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002376 MoreAsserts.assertContentsInAnyOrder(
2377 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002378 assertTrue(dpm.isAffiliatedUser());
2379
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002380 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002381 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002382 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002383 assertFalse(dpm.isAffiliatedUser());
2384
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002385 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2386 dpm.setAffiliationIds(admin2, userAffiliationIds);
2387 assertTrue(dpm.isAffiliatedUser());
2388 dpm.clearProfileOwner(admin2);
2389 assertFalse(dpm.isAffiliatedUser());
2390
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002391 // Check that the system user remains affiliated.
2392 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2393 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002394
2395 // Clear the device owner - the user becomes unaffiliated.
2396 clearDeviceOwner();
2397 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002398 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002399
2400 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002401 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002402 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2403 }
2404
2405 public void testSetUserProvisioningState_permission() throws Exception {
2406 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002407
2408 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2409 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2410 }
2411
2412 public void testSetUserProvisioningState_unprivileged() throws Exception {
2413 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002414 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2415 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2416 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002417 }
2418
2419 public void testSetUserProvisioningState_noManagement() {
2420 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002421 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002422 assertExpectException(IllegalStateException.class,
2423 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2424 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2425 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002426 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2427 }
2428
2429 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2430 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2431 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002432
2433 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2434 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2435 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2436 }
2437
2438 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2439 throws Exception {
2440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2441 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002442
2443 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2444 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2445 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2446 }
2447
2448 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2449 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2450 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002451
2452 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2453 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2454 }
2455
2456 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2457 throws Exception {
2458 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002459
2460 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2461 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2462 DevicePolicyManager.STATE_USER_UNMANAGED);
2463 }
2464
2465 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2466 throws Exception {
2467 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002468
2469 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2470 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2471 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2472 }
2473
2474 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2475 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002476
2477 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2478 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2479 }
2480
2481 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2482 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002483
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002484 assertExpectException(IllegalStateException.class,
2485 /* messageRegex= */ "Cannot move to user provisioning state",
2486 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2487 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2488 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002489 }
2490
2491 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2492 throws Exception {
2493 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002494
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002495 assertExpectException(IllegalStateException.class,
2496 /* messageRegex= */ "Cannot move to user provisioning state",
2497 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2498 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2499 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002500 }
2501
2502 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002503 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2504 mContext.callerPermissions.add(permission.MANAGE_USERS);
2505
Alan Treadwayafad8782016-01-19 15:15:08 +00002506 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2507 for (int state : states) {
2508 dpm.setUserProvisioningState(state, userId);
2509 assertEquals(state, dpm.getUserProvisioningState());
2510 }
2511 }
2512
2513 private void setupProfileOwner() throws Exception {
2514 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2515
2516 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2517 dpm.setActiveAdmin(admin1, false);
2518 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2519
2520 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2521 }
2522
2523 private void setupDeviceOwner() throws Exception {
2524 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2525
2526 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2527 dpm.setActiveAdmin(admin1, false);
2528 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2529
2530 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2531 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002532
2533 public void testSetMaximumTimeToLock() {
2534 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2535
2536 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2537 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2538
Pavel Grafov75c0a892017-05-18 17:28:27 +01002539 reset(getServices().powerManagerInternal);
2540 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002541
2542 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002543 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2544 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002545 reset(getServices().powerManagerInternal);
2546 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002547
2548 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002549 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2550 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002551 reset(getServices().powerManagerInternal);
2552 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002553
2554 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002555 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2556 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002557 reset(getServices().powerManagerInternal);
2558 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002559
2560 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002561 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2562 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002563 reset(getServices().powerManagerInternal);
2564 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002565
2566 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002567 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2568 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002569 reset(getServices().powerManagerInternal);
2570 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002571
2572 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002573 reset(getServices().powerManagerInternal);
2574 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002575
Pavel Grafov28939982017-10-03 15:11:52 +01002576 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2577 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2578 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002579 reset(getServices().powerManagerInternal);
2580 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002581
2582 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002583 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2584 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002585 reset(getServices().powerManagerInternal);
2586 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002587
Pavel Grafov28939982017-10-03 15:11:52 +01002588 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002589 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002590 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2591 verifyStayOnWhilePluggedCleared(false);
2592 }
2593
2594 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2595 // uses separate challenge.
2596 public void testSetMaximumTimeToLockProfile() throws Exception {
2597 final int PROFILE_USER = 15;
2598 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2599 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2600 mContext.binder.callingUid = PROFILE_ADMIN;
2601 final DevicePolicyManagerInternal dpmi =
2602 LocalServices.getService(DevicePolicyManagerInternal.class);
2603
2604 dpm.setMaximumTimeToLock(admin1, 0);
2605
2606 reset(getServices().powerManagerInternal);
2607 reset(getServices().settings);
2608
2609 // First add timeout for the profile.
2610 dpm.setMaximumTimeToLock(admin1, 10);
2611 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2612
2613 reset(getServices().powerManagerInternal);
2614 reset(getServices().settings);
2615
2616 // Add separate challenge
2617 when(getServices().lockPatternUtils
2618 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2619 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2620
2621 verifyScreenTimeoutCall(10L, PROFILE_USER);
2622 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2623
2624 reset(getServices().powerManagerInternal);
2625 reset(getServices().settings);
2626
2627 // Remove the timeout.
2628 dpm.setMaximumTimeToLock(admin1, 0);
2629 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2630 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2631
2632 reset(getServices().powerManagerInternal);
2633 reset(getServices().settings);
2634
2635 // Add it back.
2636 dpm.setMaximumTimeToLock(admin1, 10);
2637 verifyScreenTimeoutCall(10L, PROFILE_USER);
2638 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2639
2640 reset(getServices().powerManagerInternal);
2641 reset(getServices().settings);
2642
2643 // Remove separate challenge.
2644 reset(getServices().lockPatternUtils);
2645 when(getServices().lockPatternUtils
2646 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2647 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2648
2649 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2650 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2651
2652 reset(getServices().powerManagerInternal);
2653 reset(getServices().settings);
2654
2655 // Remove the timeout.
2656 dpm.setMaximumTimeToLock(admin1, 0);
2657 verifyScreenTimeoutCall(null, PROFILE_USER);
2658 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002659 }
2660
Michal Karpinski943aabd2016-10-06 11:09:25 +01002661 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2662 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2663 setupDeviceOwner();
2664 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2665
Michal Karpinskid084ca52017-01-18 15:54:18 +00002666 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2667 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2668 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2669 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2670 - ONE_MINUTE;
2671
2672 // verify that the minimum timeout cannot be modified on user builds (system property is
2673 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002674 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002675
2676 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2677 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2678 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2679
Pavel Grafov75c0a892017-05-18 17:28:27 +01002680 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002681
2682 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002683 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002684
Michal Karpinskid084ca52017-01-18 15:54:18 +00002685 // reset to default (0 means the admin is not participating, so default should be returned)
2686 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002687
2688 // aggregation should be the default if unset by any admin
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2690 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2691
2692 // admin not participating by default
2693 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2694
2695 //clamping from the top
2696 dpm.setRequiredStrongAuthTimeout(admin1,
2697 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2699 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2700 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2701 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2702
Michal Karpinskid084ca52017-01-18 15:54:18 +00002703 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002704 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2705 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2706 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2707 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2708
2709 // clamping from the bottom
2710 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2711 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2712 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2713
Michal Karpinskid084ca52017-01-18 15:54:18 +00002714 // values within range
2715 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2716 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2717 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2718
2719 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2720 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2721 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002722
2723 // reset to default
2724 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2725 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2726 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2727 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2728
2729 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002730 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2731 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002732 }
2733
Pavel Grafov28939982017-10-03 15:11:52 +01002734 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002735 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002736 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002737 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002738 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002739 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002740 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002741 }
Pavel Grafov28939982017-10-03 15:11:52 +01002742 }
2743
2744 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002745 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2746 // UnfinishedVerificationException.
2747 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002748
Esteban Talavera01576862016-12-15 11:16:44 +00002749 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002750 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002751 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002752 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002753 .thenReturn(false);
2754 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002755 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2756 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002757 .thenReturn(true);
2758 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2759
2760 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002761 }
Victor Chang3e794af2016-03-04 13:48:17 +00002762
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002763 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2764 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002765 mContext.packageName = admin1.getPackageName();
2766 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002767 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2768 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2769 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2770 false);
2771 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2772 }
2773
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002774 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2775 setup_DeviceAdminFeatureOff();
2776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2777 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2778 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2779 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2780 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2781 assertCheckProvisioningPreCondition(
2782 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2783 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2784 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2785 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2786 }
2787
Esteban Talavera01576862016-12-15 11:16:44 +00002788 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002789 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002790 .thenReturn(false);
2791 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002792 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2793 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002794 .thenReturn(true);
2795 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2796
2797 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002798 }
Victor Chang3e794af2016-03-04 13:48:17 +00002799
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002800 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2801 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002802 mContext.packageName = admin1.getPackageName();
2803 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002804 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2805 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2806 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2807 false);
2808 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2809
2810 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002811 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002812 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2813 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2814 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2815 true);
2816 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2817 }
2818
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002819 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2820 setup_ManagedProfileFeatureOff();
2821 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2822 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2823 DevicePolicyManager.CODE_OK);
2824 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2825 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2826 assertCheckProvisioningPreCondition(
2827 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2828 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2829 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2830 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2831
2832 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002833 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2835 DevicePolicyManager.CODE_OK);
2836 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2837 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2838 assertCheckProvisioningPreCondition(
2839 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2840 DevicePolicyManager.CODE_OK);
2841 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2842 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2843 }
2844
Esteban Talavera01576862016-12-15 11:16:44 +00002845 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002846 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002847 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002848 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2849 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002850 .thenReturn(true);
2851 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2852
2853 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002854 }
Victor Chang3e794af2016-03-04 13:48:17 +00002855
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002856 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2857 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002858 mContext.packageName = admin1.getPackageName();
2859 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002860 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2861 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2862 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2863 false /* because of non-split user */);
2864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2865 false /* because of non-split user */);
2866 }
2867
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002868 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002869 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002870 setup_nonSplitUser_firstBoot_primaryUser();
2871 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2872 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2873 DevicePolicyManager.CODE_OK);
2874 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2875 DevicePolicyManager.CODE_OK);
2876 assertCheckProvisioningPreCondition(
2877 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2878 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2879 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2880 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2881 }
2882
Esteban Talavera01576862016-12-15 11:16:44 +00002883 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002884 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002885 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002886 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2887 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002888 .thenReturn(true);
2889 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2890
2891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002892 }
Victor Chang3e794af2016-03-04 13:48:17 +00002893
Nicolas Prevot45d29072017-01-18 16:11:19 +00002894 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2895 setDeviceOwner();
2896 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2897 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2898 }
2899
2900 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2901 setup_nonSplitUser_withDo_primaryUser();
2902 final int MANAGED_PROFILE_USER_ID = 18;
2903 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2904 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002905 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002906 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002907 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002908 true)).thenReturn(true);
2909 }
2910
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002911 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2912 throws Exception {
2913 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002914 mContext.packageName = admin1.getPackageName();
2915 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002916 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2917 false/* because of completed device setup */);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2920 false/* because of non-split user */);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2922 false/* because of non-split user */);
2923 }
2924
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002925 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2926 throws Exception {
2927 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2928 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2929 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2930 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2931 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2932 DevicePolicyManager.CODE_OK);
2933 assertCheckProvisioningPreCondition(
2934 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2935 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2936 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2937 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2938 }
2939
Nicolas Prevot45d29072017-01-18 16:11:19 +00002940 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2941 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002942 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002943 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2944
2945 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2946 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002947 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002948
2949 // COMP mode is allowed.
2950 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2951 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002952 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002953
Nicolas Prevot45d29072017-01-18 16:11:19 +00002954 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002955 assertCheckProvisioningPreCondition(
2956 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002957 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002958 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002959 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2960 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2961 }
Esteban Talavera01576862016-12-15 11:16:44 +00002962
Nicolas Prevot45d29072017-01-18 16:11:19 +00002963 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2964 setup_nonSplitUser_withDo_primaryUser();
2965 mContext.packageName = admin1.getPackageName();
2966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2967 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2968 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002969 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002970 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2971 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2972 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002973 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002974 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2975 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2976 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2977 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2978 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002979 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002980 assertCheckProvisioningPreCondition(
2981 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002982 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002983 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2985 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2986 }
Esteban Talavera01576862016-12-15 11:16:44 +00002987
Nicolas Prevot45d29072017-01-18 16:11:19 +00002988 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2989 throws Exception {
2990 setup_nonSplitUser_withDo_primaryUser();
2991 mContext.packageName = admin1.getPackageName();
2992 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002993 // The DO should not be allowed to initiate provisioning if the restriction is set by
2994 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002995 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002996 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2997 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2998 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002999 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003000 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3001 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3002 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3003 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3004 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003005 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3006
3007 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003008 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003009 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003010 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003011 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3012 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3013 }
3014
3015 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3016 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3017 mContext.packageName = admin1.getPackageName();
3018 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3019
3020 // We can delete the managed profile to create a new one, so provisioning is allowed.
3021 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3022 DevicePolicyManager.CODE_OK);
3023 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3024 assertCheckProvisioningPreCondition(
3025 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3026 DpmMockContext.ANOTHER_PACKAGE_NAME,
3027 DevicePolicyManager.CODE_OK);
3028 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3029 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3030 }
3031
3032 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3033 throws Exception {
3034 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3035 mContext.packageName = admin1.getPackageName();
3036 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003037 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003038 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3039 eq(UserHandle.SYSTEM)))
3040 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003041 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003042 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3043 eq(UserHandle.SYSTEM)))
3044 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003045
3046 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003047 assertCheckProvisioningPreCondition(
3048 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3049 DpmMockContext.ANOTHER_PACKAGE_NAME,
3050 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3051 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3052 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003053
3054 // But the device owner can still do it because it has set the restriction itself.
3055 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3056 DevicePolicyManager.CODE_OK);
3057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003058 }
3059
3060 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003061 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003062 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003063 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3064 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003065 .thenReturn(false);
3066 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3067
3068 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003069 }
Victor Chang3e794af2016-03-04 13:48:17 +00003070
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003071 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3072 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003073 mContext.packageName = admin1.getPackageName();
3074 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003075 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3076 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3077 false /* because canAddMoreManagedProfiles returns false */);
3078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3079 true);
3080 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3081 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003082 }
3083
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3085 throws Exception {
3086 setup_splitUser_firstBoot_systemUser();
3087 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3088 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3089 DevicePolicyManager.CODE_OK);
3090 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003091 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003092 assertCheckProvisioningPreCondition(
3093 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3094 DevicePolicyManager.CODE_OK);
3095 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3096 DevicePolicyManager.CODE_SYSTEM_USER);
3097 }
3098
Esteban Talavera01576862016-12-15 11:16:44 +00003099 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003100 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003101 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003102 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3103 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003104 .thenReturn(false);
3105 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3106
3107 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003108 }
Victor Chang3e794af2016-03-04 13:48:17 +00003109
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003110 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3111 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003112 mContext.packageName = admin1.getPackageName();
3113 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003114 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3115 true/* it's undefined behavior. Can be changed into false in the future */);
3116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3117 false /* because canAddMoreManagedProfiles returns false */);
3118 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3119 true/* it's undefined behavior. Can be changed into false in the future */);
3120 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3121 false/* because calling uid is system user */);
3122 }
3123
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003124 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3125 throws Exception {
3126 setup_splitUser_afterDeviceSetup_systemUser();
3127 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3128 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3129 DevicePolicyManager.CODE_OK);
3130 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003131 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003132 assertCheckProvisioningPreCondition(
3133 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3134 DevicePolicyManager.CODE_OK);
3135 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3136 DevicePolicyManager.CODE_SYSTEM_USER);
3137 }
3138
Esteban Talavera01576862016-12-15 11:16:44 +00003139 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003140 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003141 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003142 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3143 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003144 true)).thenReturn(true);
3145 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3146
3147 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003148 }
Victor Chang3e794af2016-03-04 13:48:17 +00003149
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003150 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3151 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003152 mContext.packageName = admin1.getPackageName();
3153 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003154 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3155 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3156 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3157 true);
3158 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003159 }
3160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003162 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003163 setup_splitUser_firstBoot_primaryUser();
3164 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3165 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3166 DevicePolicyManager.CODE_OK);
3167 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3168 DevicePolicyManager.CODE_OK);
3169 assertCheckProvisioningPreCondition(
3170 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3171 DevicePolicyManager.CODE_OK);
3172 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3173 DevicePolicyManager.CODE_OK);
3174 }
3175
Esteban Talavera01576862016-12-15 11:16:44 +00003176 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003177 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003178 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003179 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3180 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003181 true)).thenReturn(true);
3182 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3183
3184 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003185 }
Victor Chang3e794af2016-03-04 13:48:17 +00003186
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003187 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3188 throws Exception {
3189 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003190 mContext.packageName = admin1.getPackageName();
3191 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003192 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3193 true/* it's undefined behavior. Can be changed into false in the future */);
3194 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3195 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3196 true/* it's undefined behavior. Can be changed into false in the future */);
3197 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3198 false/* because user setup completed */);
3199 }
3200
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003201 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003202 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003203 setup_splitUser_afterDeviceSetup_primaryUser();
3204 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3205 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3206 DevicePolicyManager.CODE_OK);
3207 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3208 DevicePolicyManager.CODE_OK);
3209 assertCheckProvisioningPreCondition(
3210 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3211 DevicePolicyManager.CODE_OK);
3212 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3213 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3214 }
3215
Esteban Talavera01576862016-12-15 11:16:44 +00003216 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003217 setDeviceOwner();
3218
Pavel Grafov75c0a892017-05-18 17:28:27 +01003219 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003220 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003221 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3222 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003223 .thenReturn(false);
3224 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3225
3226 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003227 }
Victor Chang3e794af2016-03-04 13:48:17 +00003228
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003229 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3230 throws Exception {
3231 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003232 mContext.packageName = admin1.getPackageName();
3233 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003234 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3235 false /* can't provision managed profile on system user */);
3236 }
3237
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003239 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3241 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3243 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3244 }
3245
3246 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003247 setDeviceOwner();
3248
Pavel Grafov75c0a892017-05-18 17:28:27 +01003249 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003250 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003251 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3252 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003253 true)).thenReturn(true);
3254 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3255
3256 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003257 }
Victor Chang3e794af2016-03-04 13:48:17 +00003258
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003259 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3260 throws Exception {
3261 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003262 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3263 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003264 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3265 }
3266
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003268 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003269 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3270 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003271
3272 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003273 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3274 DevicePolicyManager.CODE_OK);
3275 }
3276
3277 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003278 setDeviceOwner();
3279
Pavel Grafov75c0a892017-05-18 17:28:27 +01003280 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003281 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003282 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3283 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003284 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3285 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003286 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003287 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003288 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003289 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003290 true)).thenReturn(true);
3291 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3292
3293 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003295
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003296 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3297 throws Exception {
3298 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003299 mContext.packageName = admin1.getPackageName();
3300 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003301 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3302 }
3303
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003304 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3305 throws Exception {
3306 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3307 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3308 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3309 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3310 }
3311
3312 public void testCheckProvisioningPreCondition_permission() {
3313 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003314 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3315 () -> dpm.checkProvisioningPreCondition(
3316 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003317 }
3318
Victor Chang3577ed22016-08-25 18:49:26 +01003319 public void testForceUpdateUserSetupComplete_permission() {
3320 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003321 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3322 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003323 }
3324
3325 public void testForceUpdateUserSetupComplete_systemUser() {
3326 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3327 // GIVEN calling from user 20
3328 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003329 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3330 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003331 }
3332
3333 public void testForceUpdateUserSetupComplete_userbuild() {
3334 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3335 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3336
3337 final int userId = UserHandle.USER_SYSTEM;
3338 // GIVEN userComplete is false in SettingsProvider
3339 setUserSetupCompleteForUser(false, userId);
3340
3341 // GIVEN userComplete is true in DPM
3342 DevicePolicyManagerService.DevicePolicyData userData =
3343 new DevicePolicyManagerService.DevicePolicyData(userId);
3344 userData.mUserSetupComplete = true;
3345 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3346
3347 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003348 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003349
3350 assertTrue(dpms.hasUserSetupCompleted());
3351
3352 dpm.forceUpdateUserSetupComplete();
3353
3354 // THEN the state in dpms is not changed
3355 assertTrue(dpms.hasUserSetupCompleted());
3356 }
3357
3358 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3359 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3360 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3361
3362 final int userId = UserHandle.USER_SYSTEM;
3363 // GIVEN userComplete is false in SettingsProvider
3364 setUserSetupCompleteForUser(false, userId);
3365
3366 // GIVEN userComplete is true in DPM
3367 DevicePolicyManagerService.DevicePolicyData userData =
3368 new DevicePolicyManagerService.DevicePolicyData(userId);
3369 userData.mUserSetupComplete = true;
3370 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3371
3372 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003373 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003374
3375 assertTrue(dpms.hasUserSetupCompleted());
3376
3377 dpm.forceUpdateUserSetupComplete();
3378
3379 // THEN the state in dpms is not changed
3380 assertFalse(dpms.hasUserSetupCompleted());
3381 }
3382
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003383 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003384 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003385 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003386
3387 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3388 runAsCaller(mAdmin1Context, dpms, dpm -> {
3389 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3390 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003391 }
3392
3393 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3394 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3395 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003396
3397 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3398 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003399 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003400 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3401 .thenReturn(true);
3402
3403 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003404 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003405
3406 // Enabling logging should not change the timestamp.
3407 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003408 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003409 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003410 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003411 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003412 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003413
3414 // Retrieving the logs should update the timestamp.
3415 final long beforeRetrieval = System.currentTimeMillis();
3416 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003417 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003418 final long afterRetrieval = System.currentTimeMillis();
3419 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3420 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3421
3422 // Retrieving the pre-boot logs should update the timestamp.
3423 Thread.sleep(2);
3424 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003425 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003426 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3427
3428 // Checking the timestamp again should not change it.
3429 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003430 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003431
3432 // Retrieving the logs again should update the timestamp.
3433 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003434 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003435 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3436
3437 // Disabling logging should not change the timestamp.
3438 Thread.sleep(2);
3439 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003440 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003441
3442 // Restarting the DPMS should not lose the timestamp.
3443 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003444 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003445
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003446 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3447 mContext.binder.callingUid = 1234567;
3448 mContext.callerPermissions.add(permission.MANAGE_USERS);
3449 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3450 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3451
3452 // System can retrieve the timestamp.
3453 mContext.binder.clearCallingIdentity();
3454 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3455
3456 // Removing the device owner should clear the timestamp.
3457 clearDeviceOwner();
3458 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003459 }
3460
yuemingw0de748d2017-11-15 19:22:27 +00003461 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3462 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3463 setupDeviceOwner();
3464 assertExpectException(SecurityException.class, null, () ->
3465 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3466 }
3467
yuemingwc0281f12018-03-28 15:58:49 +01003468 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003469 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3470 setupDeviceOwner();
3471 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003472 verify(getServices().settings).settingsSystemPutStringForUser(
3473 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3474 }
3475
3476 public void testSetSystemSettingWithPO() throws Exception {
3477 setupProfileOwner();
3478 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3479 verify(getServices().settings).settingsSystemPutStringForUser(
3480 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003481 }
3482
yuemingwe43cdf72017-10-12 16:52:11 +01003483 public void testSetTime() throws Exception {
3484 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3485 setupDeviceOwner();
3486 dpm.setTime(admin1, 0);
3487 verify(getServices().alarmManager).setTime(0);
3488 }
3489
3490 public void testSetTimeFailWithPO() throws Exception {
3491 setupProfileOwner();
3492 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3493 }
3494
3495 public void testSetTimeWithAutoTimeOn() throws Exception {
3496 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3497 setupDeviceOwner();
3498 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3499 .thenReturn(1);
3500 assertFalse(dpm.setTime(admin1, 0));
3501 }
3502
3503 public void testSetTimeZone() throws Exception {
3504 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3505 setupDeviceOwner();
3506 dpm.setTimeZone(admin1, "Asia/Shanghai");
3507 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3508 }
3509
3510 public void testSetTimeZoneFailWithPO() throws Exception {
3511 setupProfileOwner();
3512 assertExpectException(SecurityException.class, null,
3513 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3514 }
3515
3516 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3517 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3518 setupDeviceOwner();
3519 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3520 .thenReturn(1);
3521 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3522 }
3523
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003524 public void testGetLastBugReportRequestTime() throws Exception {
3525 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3526 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003527
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003528 mContext.packageName = admin1.getPackageName();
3529 mContext.applicationInfo = new ApplicationInfo();
3530 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3531 .thenReturn(Color.WHITE);
3532 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3533 anyObject())).thenReturn(Color.WHITE);
3534
Esteban Talaverad36dd152016-12-15 08:51:45 +00003535 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3536 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003537 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003538
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003539 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003540 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003541
3542 // Requesting a bug report should update the timestamp.
3543 final long beforeRequest = System.currentTimeMillis();
3544 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003545 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003546 final long afterRequest = System.currentTimeMillis();
3547 assertTrue(bugReportRequestTime >= beforeRequest);
3548 assertTrue(bugReportRequestTime <= afterRequest);
3549
3550 // Checking the timestamp again should not change it.
3551 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003552 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003553
3554 // Restarting the DPMS should not lose the timestamp.
3555 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003556 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003557
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003558 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3559 mContext.binder.callingUid = 1234567;
3560 mContext.callerPermissions.add(permission.MANAGE_USERS);
3561 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3562 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3563
3564 // System can retrieve the timestamp.
3565 mContext.binder.clearCallingIdentity();
3566 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3567
3568 // Removing the device owner should clear the timestamp.
3569 clearDeviceOwner();
3570 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003571 }
3572
3573 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3574 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3575 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003576 mContext.packageName = admin1.getPackageName();
3577 mContext.applicationInfo = new ApplicationInfo();
3578 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3579 .thenReturn(Color.WHITE);
3580 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3581 anyObject())).thenReturn(Color.WHITE);
3582
3583 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3584 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003585 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003586 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003587 .thenReturn(true);
3588
3589 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003590 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003591
3592 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3593 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003594 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003595
3596 // Enabling logging should not change the timestamp.
3597 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003598 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003599
3600 // Retrieving the logs should update the timestamp.
3601 final long beforeRetrieval = System.currentTimeMillis();
3602 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003603 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003604 final long afterRetrieval = System.currentTimeMillis();
3605 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3606 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3607
3608 // Checking the timestamp again should not change it.
3609 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003610 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003611
3612 // Retrieving the logs again should update the timestamp.
3613 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003614 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003615 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3616
3617 // Disabling logging should not change the timestamp.
3618 Thread.sleep(2);
3619 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003620 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003621
3622 // Restarting the DPMS should not lose the timestamp.
3623 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003624 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3625
3626 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3627 mContext.binder.callingUid = 1234567;
3628 mContext.callerPermissions.add(permission.MANAGE_USERS);
3629 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3630 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3631
3632 // System can retrieve the timestamp.
3633 mContext.binder.clearCallingIdentity();
3634 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3635
3636 // Removing the device owner should clear the timestamp.
3637 clearDeviceOwner();
3638 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003639 }
3640
Tony Mak2f26b792016-11-28 17:54:51 +00003641 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3642 // Setup device owner.
3643 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3644 setupDeviceOwner();
3645
3646 // Only device owner is setup, the result list should be empty.
3647 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3648 MoreAsserts.assertEmpty(targetUsers);
3649
3650 // Setup a managed profile managed by the same admin.
3651 final int MANAGED_PROFILE_USER_ID = 15;
3652 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3653 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3654
3655 // Add a secondary user, it should never talk with.
3656 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003657 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003658
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003659 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3660 // other.
3661 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3662 MoreAsserts.assertEmpty(targetUsers);
3663
3664 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3665 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3666 MoreAsserts.assertEmpty(targetUsers);
3667
3668 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003669 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3671 dpm.setAffiliationIds(admin1, userAffiliationIds);
3672
3673 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3674 dpm.setAffiliationIds(admin1, userAffiliationIds);
3675
Tony Mak2f26b792016-11-28 17:54:51 +00003676 // Calling from device owner admin, the result list should just contain the managed
3677 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003678 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003679 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3680 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3681
3682 // Calling from managed profile admin, the result list should just contain the system
3683 // user id.
3684 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3685 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3686 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003687
3688 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003689 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003690
3691 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3692 // to each other.
3693 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3694 MoreAsserts.assertEmpty(targetUsers);
3695
3696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3697 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3698 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003699 }
3700
3701 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3702 // Setup a device owner.
3703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3704 setupDeviceOwner();
3705
3706 // Set up a managed profile managed by different package.
3707 final int MANAGED_PROFILE_USER_ID = 15;
3708 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3709 final ComponentName adminDifferentPackage =
3710 new ComponentName("another.package", "whatever.class");
3711 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3712
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003713 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003714 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003715 dpm.setAffiliationIds(admin1, userAffiliationIds);
3716
3717 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3718 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3719
Tony Mak2f26b792016-11-28 17:54:51 +00003720 // Calling from device owner admin, we should get zero bind device admin target users as
3721 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003722 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003723 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3724 MoreAsserts.assertEmpty(targetUsers);
3725
3726 // Calling from managed profile admin, we should still get zero target users for the same
3727 // reason.
3728 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3729 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3730 MoreAsserts.assertEmpty(targetUsers);
3731 }
3732
Jason Parks3c13b642017-11-28 15:39:43 -06003733 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003734 verifyLockTaskState(userId, new String[0],
3735 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003736 }
3737
3738 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3739 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003740 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003741 }
3742
3743 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3744 int flags) throws Exception {
3745 mContext.binder.callingUid = uid;
3746 dpm.setLockTaskPackages(who, packages);
3747 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3748 for (String p : packages) {
3749 assertTrue(dpm.isLockTaskPermitted(p));
3750 }
3751 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3752 // Test to see if set lock task features can be set
3753 dpm.setLockTaskFeatures(who, flags);
3754 verifyLockTaskState(userId, packages, flags);
3755 }
3756
3757 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3758 int flags) throws Exception {
3759 mContext.binder.callingUid = uid;
3760 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3761 () -> dpm.setLockTaskPackages(who, packages));
3762 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3763 () -> dpm.getLockTaskPackages(who));
3764 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3765 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3766 () -> dpm.setLockTaskFeatures(who, flags));
3767 }
3768
Charles Hee078db72017-10-19 18:03:20 +01003769 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003770 // Setup a device owner.
3771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3772 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003773 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003774 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003775
3776 // Set up a managed profile managed by different package (package name shouldn't matter)
3777 final int MANAGED_PROFILE_USER_ID = 15;
3778 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3779 final ComponentName adminDifferentPackage =
3780 new ComponentName("another.package", "whatever.class");
3781 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003782 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3783
3784 // Setup a PO on the secondary user
3785 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3786 setAsProfileOwner(admin3);
3787 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003788
3789 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003790 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003791 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003792 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3793 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003794 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3795
3796 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3797 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003798 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3799 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003800 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003801
3802 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3803 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3804 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003805 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003806 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3807 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003808 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003809
3810 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003811 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003812 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3813 dpm.setAffiliationIds(admin1, userAffiliationIds);
3814
3815 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3816 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3817
3818 // Now the managed profile can set lock task packages.
3819 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3820 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3821 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3822 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003823 // And it can set lock task features.
3824 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003825 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003826
3827 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003828 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003829 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3830 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003831 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3832 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003833 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003834 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003835
Jason Parks3c13b642017-11-28 15:39:43 -06003836 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003837 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3838 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003839
3840 }
3841
3842 public void testLockTaskPolicyForProfileOwner() throws Exception {
3843 // Setup a PO
3844 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3845 setAsProfileOwner(admin1);
3846 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3847
3848 final String[] poPackages = {"poPackage1", "poPackage2"};
3849 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003850 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3851 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003852 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3853 poPackages, poFlags);
3854
3855 // Set up a managed profile managed by different package (package name shouldn't matter)
3856 final int MANAGED_PROFILE_USER_ID = 15;
3857 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3858 final ComponentName adminDifferentPackage =
3859 new ComponentName("another.package", "whatever.class");
3860 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3861 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3862
3863 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3864 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3865 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3866 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003867 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3868 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003869 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003870 }
3871
Benjamin Franzcaffa772018-02-05 16:36:10 +00003872 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3873 // Setup a device owner.
3874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3875 setupDeviceOwner();
3876 // Lock task policy is updated when loading user data.
3877 verifyLockTaskState(UserHandle.USER_SYSTEM);
3878
3879 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3880 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3881 assertExpectException(IllegalArgumentException.class,
3882 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3883 () -> dpm.setLockTaskFeatures(admin1, flags));
3884 }
3885
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003886 public void testIsDeviceManaged() throws Exception {
3887 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3888 setupDeviceOwner();
3889
3890 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3891 // find out that the device has a device owner.
3892 assertTrue(dpm.isDeviceManaged());
3893 mContext.binder.callingUid = 1234567;
3894 mContext.callerPermissions.add(permission.MANAGE_USERS);
3895 assertTrue(dpm.isDeviceManaged());
3896 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3897 mContext.binder.clearCallingIdentity();
3898 assertTrue(dpm.isDeviceManaged());
3899
3900 clearDeviceOwner();
3901
3902 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3903 // not have a device owner.
3904 mContext.binder.callingUid = 1234567;
3905 mContext.callerPermissions.add(permission.MANAGE_USERS);
3906 assertFalse(dpm.isDeviceManaged());
3907 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3908 mContext.binder.clearCallingIdentity();
3909 assertFalse(dpm.isDeviceManaged());
3910 }
3911
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003912 public void testDeviceOwnerOrganizationName() throws Exception {
3913 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3914 setupDeviceOwner();
3915
3916 dpm.setOrganizationName(admin1, "organization");
3917
3918 // Device owner can retrieve organization managing the device.
3919 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3920
3921 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3922 mContext.binder.callingUid = 1234567;
3923 mContext.callerPermissions.add(permission.MANAGE_USERS);
3924 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3925 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3926
3927 // System can retrieve organization managing the device.
3928 mContext.binder.clearCallingIdentity();
3929 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3930
3931 // Removing the device owner clears the organization managing the device.
3932 clearDeviceOwner();
3933 assertNull(dpm.getDeviceOwnerOrganizationName());
3934 }
3935
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003936 public void testWipeDataManagedProfile() throws Exception {
3937 final int MANAGED_PROFILE_USER_ID = 15;
3938 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3939 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3940 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3941
3942 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003943 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003944 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003945 // Get mock reason string since we throw an IAE with empty string input.
3946 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3947 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003948
3949 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003950 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003951 MANAGED_PROFILE_USER_ID);
3952 }
3953
3954 public void testWipeDataManagedProfileDisallowed() throws Exception {
3955 final int MANAGED_PROFILE_USER_ID = 15;
3956 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3957 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3958
3959 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003960 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003961 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3962
Pavel Grafov75c0a892017-05-18 17:28:27 +01003963 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003964 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3965 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3966 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003967 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3968 thenReturn("Just a test string.");
3969
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003970 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003971 // The PO is not allowed to remove the profile if the user restriction was set on the
3972 // profile by the system
3973 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3974 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003975 }
3976
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003977 public void testWipeDataDeviceOwner() throws Exception {
3978 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003979 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003980 UserManager.DISALLOW_FACTORY_RESET,
3981 UserHandle.SYSTEM))
3982 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003983 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3984 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003985
3986 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003987 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003988 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3989 /*wipeEuicc=*/ eq(false));
3990 }
3991
3992 public void testWipeEuiccDataEnabled() throws Exception {
3993 setDeviceOwner();
3994 when(getServices().userManager.getUserRestrictionSource(
3995 UserManager.DISALLOW_FACTORY_RESET,
3996 UserHandle.SYSTEM))
3997 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003998 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3999 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004000
4001 dpm.wipeData(WIPE_EUICC);
4002 verify(getServices().recoverySystem).rebootWipeUserData(
4003 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4004 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004005 }
4006
4007 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4008 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004009 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004010 UserManager.DISALLOW_FACTORY_RESET,
4011 UserHandle.SYSTEM))
4012 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004013 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4014 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004015 // The DO is not allowed to wipe the device if the user restriction was set
4016 // by the system
4017 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4018 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004019 }
4020
4021 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4022 final int MANAGED_PROFILE_USER_ID = 15;
4023 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4024 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4025
4026 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004027 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004028 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4029
Pavel Grafov75c0a892017-05-18 17:28:27 +01004030 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004031 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4032 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4033 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4034
4035 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4036 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4037
4038 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4039 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4040 // Failed password attempts on the parent user are taken into account, as there isn't a
4041 // separate work challenge.
4042 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4043 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4044 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4045
4046 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4047 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004048 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004049 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004050 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004051 }
4052
4053 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4054 throws Exception {
4055 final int MANAGED_PROFILE_USER_ID = 15;
4056 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4057 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4058
4059 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004060 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004061 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4062
Pavel Grafov75c0a892017-05-18 17:28:27 +01004063 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004064 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4065 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4066 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4067
4068 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4069 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4070
4071 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4072 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4073 // Failed password attempts on the parent user are taken into account, as there isn't a
4074 // separate work challenge.
4075 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4076 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4077 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4078
4079 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4080 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004082 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004083 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004084 }
4085
4086 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() 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_DEVICE_OWNER);
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 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4102 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004103 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004104 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4105 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004106 }
4107
4108 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4109 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004111 UserManager.DISALLOW_FACTORY_RESET,
4112 UserHandle.SYSTEM))
4113 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4114
4115 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4116
4117 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4118 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4119 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4120 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4121 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4122
4123 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004124 verifyZeroInteractions(getServices().recoverySystem);
4125 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004126 .removeUserEvenWhenDisallowed(anyInt());
4127 }
4128
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004129 public void testGetPermissionGrantState() throws Exception {
4130 final String permission = "some.permission";
4131 final String app1 = "com.example.app1";
4132 final String app2 = "com.example.app2";
4133
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004135 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004136 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004137 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004138 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004139 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4140 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004141 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004142 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004143 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004144 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004145 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004146 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4147
4148 // System can retrieve permission grant state.
4149 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004150 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004151 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4152 dpm.getPermissionGrantState(null, app1, permission));
4153 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4154 dpm.getPermissionGrantState(null, app2, permission));
4155
4156 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004157 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4158 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004159 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4160 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004161
4162 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004163 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4164 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004165 setAsProfileOwner(admin1);
4166 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4167 dpm.getPermissionGrantState(admin1, app1, permission));
4168 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4169 dpm.getPermissionGrantState(admin1, app2, permission));
4170 }
4171
Rubin Xuaab7a412016-12-30 21:13:29 +00004172 public void testResetPasswordWithToken() throws Exception {
4173 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4174 setupDeviceOwner();
4175 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004176 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4177 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4178
Rubin Xuaab7a412016-12-30 21:13:29 +00004179 // test adding a token
4180 final byte[] token = new byte[32];
4181 final long handle = 123456;
4182 final String password = "password";
Pavel Grafov75c0a892017-05-18 17:28:27 +01004183 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004184 .thenReturn(handle);
4185 assertTrue(dpm.setResetPasswordToken(admin1, token));
4186
4187 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004188 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004189 .thenReturn(true);
4190 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4191
4192 // test reset password with token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004193 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password),
Rubin Xu7cf45092017-08-28 11:47:35 +01004194 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
4195 eq(DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004196 eq(UserHandle.USER_SYSTEM)))
4197 .thenReturn(true);
4198 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4199
4200 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004202 .thenReturn(true);
4203 assertTrue(dpm.clearResetPasswordToken(admin1));
4204 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004205
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004206 public void testIsActivePasswordSufficient() throws Exception {
4207 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4208 mContext.packageName = admin1.getPackageName();
4209 setupDeviceOwner();
4210
4211 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4212 dpm.setPasswordMinimumLength(admin1, 8);
4213 dpm.setPasswordMinimumLetters(admin1, 6);
4214 dpm.setPasswordMinimumLowerCase(admin1, 3);
4215 dpm.setPasswordMinimumUpperCase(admin1, 1);
4216 dpm.setPasswordMinimumNonLetter(admin1, 1);
4217 dpm.setPasswordMinimumNumeric(admin1, 1);
4218 dpm.setPasswordMinimumSymbols(admin1, 0);
4219
Rubin Xucc391c22018-01-02 20:37:35 +00004220 reset(mContext.spiedContext);
4221
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004222 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4223 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4224 8, 2,
4225 6, 1,
4226 0, 1);
4227
4228 setActivePasswordState(passwordMetricsNoSymbols);
4229 assertTrue(dpm.isActivePasswordSufficient());
4230
4231 initializeDpms();
4232 reset(mContext.spiedContext);
4233 assertTrue(dpm.isActivePasswordSufficient());
4234
4235 // This call simulates the user entering the password for the first time after a reboot.
4236 // This causes password metrics to be reloaded into memory. Until this happens,
4237 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4238 // even if the DPC changes password requirements so that the password no longer meets the
4239 // requirements. This is a known limitation of the current implementation of
4240 // isActivePasswordSufficient() - see b/34218769.
4241 setActivePasswordState(passwordMetricsNoSymbols);
4242 assertTrue(dpm.isActivePasswordSufficient());
4243
4244 dpm.setPasswordMinimumSymbols(admin1, 1);
4245 // This assertion would fail if we had not called setActivePasswordState() again after
4246 // initializeDpms() - see previous comment.
4247 assertFalse(dpm.isActivePasswordSufficient());
4248
4249 initializeDpms();
4250 reset(mContext.spiedContext);
4251 assertFalse(dpm.isActivePasswordSufficient());
4252
4253 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4254 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4255 7, 2,
4256 5, 1,
4257 1, 2);
4258
4259 setActivePasswordState(passwordMetricsWithSymbols);
4260 assertTrue(dpm.isActivePasswordSufficient());
4261 }
4262
Pavel Grafov75c0a892017-05-18 17:28:27 +01004263 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4264 throws Exception {
4265 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004266 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004267
Pavel Grafov75c0a892017-05-18 17:28:27 +01004268 dpm.setActivePasswordState(passwordMetrics, userHandle);
4269 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004270
Rubin Xucc391c22018-01-02 20:37:35 +00004271 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4272 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004273 // This broadcast should be sent 4 times:
4274 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4275 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4276 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4277 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4278 // the password change is relevant to and another with the credential owner of said
4279 // userId.
4280 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004281 MockUtils.checkIntentAction(
4282 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4283 MockUtils.checkUserHandle(userHandle));
4284
Pavel Grafov75c0a892017-05-18 17:28:27 +01004285 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4286 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004287 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004288
4289 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4290 MockUtils.checkIntent(intent),
4291 MockUtils.checkUserHandle(userHandle));
4292
4293 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4294 // let it finish with system uid, otherwise it will throw and crash.
4295 flushTasks();
4296
4297 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004298 }
4299
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004300 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4301 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4302 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4303 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4304 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4305 DpmMockContext.SYSTEM_UID);
4306 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4307 DpmMockContext.SYSTEM_UID);
4308
4309 // Set up a device owner.
4310 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004311 setupDeviceOwner();
4312
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004313 // First and second user set IMEs manually.
4314 mContext.binder.callingUid = firstUserSystemUid;
4315 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4316 mContext.binder.callingUid = secondUserSystemUid;
4317 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004318
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004319 // Device owner changes IME for first user.
4320 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004321 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004322 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004323 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004324 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004325 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004326 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004327 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4328 mContext.binder.callingUid = firstUserSystemUid;
4329 assertTrue(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 // Second user changes IME manually.
4334 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4335 mContext.binder.callingUid = firstUserSystemUid;
4336 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4337 mContext.binder.callingUid = secondUserSystemUid;
4338 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004339
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004340 // First user changes IME manually.
4341 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4342 mContext.binder.callingUid = firstUserSystemUid;
4343 assertFalse(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 // Device owner changes IME for first user again.
4348 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004349 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004350 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004351 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004352 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004353 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004354 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4355 mContext.binder.callingUid = firstUserSystemUid;
4356 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4357 mContext.binder.callingUid = secondUserSystemUid;
4358 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004359
4360 // Restarting the DPMS should not lose information.
4361 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004362 mContext.binder.callingUid = firstUserSystemUid;
4363 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4364 mContext.binder.callingUid = secondUserSystemUid;
4365 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004366
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004367 // Device owner can find out whether it set the current IME itself.
4368 mContext.binder.callingUid = deviceOwnerUid;
4369 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004370
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004371 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004372 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004373 mContext.binder.callingUid = firstUserSystemUid;
4374 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4375 mContext.binder.callingUid = secondUserSystemUid;
4376 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004377 }
4378
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004379 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4380 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4381 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4382 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4383 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4384 DpmMockContext.SYSTEM_UID);
4385 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4386 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004387
4388 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004389 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004390 setupProfileOwner();
4391
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004392 // First and second user set IMEs manually.
4393 mContext.binder.callingUid = firstUserSystemUid;
4394 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4395 mContext.binder.callingUid = secondUserSystemUid;
4396 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004397
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004398 // Profile owner changes IME for second user.
4399 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004400 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004401 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004402 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004403 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004404 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004405 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004406 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4407 mContext.binder.callingUid = firstUserSystemUid;
4408 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4409 mContext.binder.callingUid = secondUserSystemUid;
4410 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004411
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004412 // First user changes IME manually.
4413 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4414 mContext.binder.callingUid = firstUserSystemUid;
4415 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4416 mContext.binder.callingUid = secondUserSystemUid;
4417 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004418
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004419 // Second user changes IME manually.
4420 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4421 mContext.binder.callingUid = firstUserSystemUid;
4422 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4423 mContext.binder.callingUid = secondUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004425
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004426 // Profile owner changes IME for second user again.
4427 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004428 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004429 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004430 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004431 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004432 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004433 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4434 mContext.binder.callingUid = firstUserSystemUid;
4435 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4436 mContext.binder.callingUid = secondUserSystemUid;
4437 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004438
4439 // Restarting the DPMS should not lose information.
4440 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004441 mContext.binder.callingUid = firstUserSystemUid;
4442 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4443 mContext.binder.callingUid = secondUserSystemUid;
4444 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004445
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004446 // Profile owner can find out whether it set the current IME itself.
4447 mContext.binder.callingUid = profileOwnerUid;
4448 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004449
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004450 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004451 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004452 mContext.binder.callingUid = firstUserSystemUid;
4453 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4454 mContext.binder.callingUid = secondUserSystemUid;
4455 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004456 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004457
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004458 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4459 throws Exception {
4460 // Set up a device owner.
4461 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4462 setupDeviceOwner();
4463 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4464 }
4465
4466 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4467 throws Exception {
4468 // Set up a profile owner.
4469 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4470 setupProfileOwner();
4471 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4472 }
4473
4474 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4475 int adminUid) throws Exception {
4476 mContext.binder.callingUid = adminUid;
4477 final int userId = UserHandle.getUserId(adminUid);
4478
4479 final String packageName = "some.package";
4480 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4481 admin1, Collections.singletonList(packageName)));
4482 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4483
4484 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4485 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4486
4487 // Attempt to set to empty list (which means no listener is whitelisted)
4488 mContext.binder.callingUid = adminUid;
4489 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004490 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004491 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4492
4493 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4494 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4495 }
4496
4497 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4498 // Set up a managed profile
4499 final int MANAGED_PROFILE_USER_ID = 15;
4500 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4501 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4502 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4503
4504 final String permittedListener = "some.package";
4505 setupPackageInPackageManager(
4506 permittedListener,
4507 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4508 /*appId=*/ 12345, /*flags=*/ 0);
4509
4510 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4511 admin1, Collections.singletonList(permittedListener)));
4512
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004513 // isNotificationListenerServicePermitted should throw if not called from System.
4514 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4515 () -> dpms.isNotificationListenerServicePermitted(
4516 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004517
4518 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4519 assertTrue(dpms.isNotificationListenerServicePermitted(
4520 permittedListener, MANAGED_PROFILE_USER_ID));
4521 }
4522
4523 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4524 throws Exception {
4525 // Set up a managed profile
4526 final int MANAGED_PROFILE_USER_ID = 15;
4527 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4528 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4529 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4530
4531 final String permittedListener = "permitted.package";
4532 int appId = 12345;
4533 setupPackageInPackageManager(
4534 permittedListener,
4535 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4536 appId, /*flags=*/ 0);
4537
4538 final String notPermittedListener = "not.permitted.package";
4539 setupPackageInPackageManager(
4540 notPermittedListener,
4541 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4542 ++appId, /*flags=*/ 0);
4543
4544 final String systemListener = "system.package";
4545 setupPackageInPackageManager(
4546 systemListener,
4547 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4548 ++appId, ApplicationInfo.FLAG_SYSTEM);
4549
4550 // By default all packages are allowed
4551 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4552
4553 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4554 assertTrue(dpms.isNotificationListenerServicePermitted(
4555 permittedListener, MANAGED_PROFILE_USER_ID));
4556 assertTrue(dpms.isNotificationListenerServicePermitted(
4557 notPermittedListener, MANAGED_PROFILE_USER_ID));
4558 assertTrue(dpms.isNotificationListenerServicePermitted(
4559 systemListener, MANAGED_PROFILE_USER_ID));
4560
4561 // Setting only one package in the whitelist
4562 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4563 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4564 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004565 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004566 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4567 assertEquals(1, permittedListeners.size());
4568 assertEquals(permittedListener, permittedListeners.get(0));
4569
4570 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4571 assertTrue(dpms.isNotificationListenerServicePermitted(
4572 permittedListener, MANAGED_PROFILE_USER_ID));
4573 assertFalse(dpms.isNotificationListenerServicePermitted(
4574 notPermittedListener, MANAGED_PROFILE_USER_ID));
4575 // System packages are always allowed (even if not in the whitelist)
4576 assertTrue(dpms.isNotificationListenerServicePermitted(
4577 systemListener, MANAGED_PROFILE_USER_ID));
4578
4579 // Setting an empty whitelist - only system listeners allowed
4580 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4581 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004582 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004583 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4584
4585 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4586 assertFalse(dpms.isNotificationListenerServicePermitted(
4587 permittedListener, MANAGED_PROFILE_USER_ID));
4588 assertFalse(dpms.isNotificationListenerServicePermitted(
4589 notPermittedListener, MANAGED_PROFILE_USER_ID));
4590 // System packages are always allowed (even if not in the whitelist)
4591 assertTrue(dpms.isNotificationListenerServicePermitted(
4592 systemListener, MANAGED_PROFILE_USER_ID));
4593
4594 // Setting a null whitelist - all listeners allowed
4595 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4596 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4597 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4598
4599 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4600 assertTrue(dpms.isNotificationListenerServicePermitted(
4601 permittedListener, MANAGED_PROFILE_USER_ID));
4602 assertTrue(dpms.isNotificationListenerServicePermitted(
4603 notPermittedListener, MANAGED_PROFILE_USER_ID));
4604 assertTrue(dpms.isNotificationListenerServicePermitted(
4605 systemListener, MANAGED_PROFILE_USER_ID));
4606 }
4607
4608 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4609 throws Exception {
4610 // Set up a managed profile
4611 final int MANAGED_PROFILE_USER_ID = 15;
4612 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4613 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4614 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4615
4616 final String nonSystemPackage = "non.system.package";
4617 int appId = 12345;
4618 setupPackageInPackageManager(
4619 nonSystemPackage,
4620 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4621 appId, /*flags=*/ 0);
4622
4623 final String systemListener = "system.package";
4624 setupPackageInPackageManager(
4625 systemListener,
4626 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4627 ++appId, ApplicationInfo.FLAG_SYSTEM);
4628
4629 // By default all packages are allowed (for all profiles)
4630 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4631
4632 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4633 assertTrue(dpms.isNotificationListenerServicePermitted(
4634 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4635 assertTrue(dpms.isNotificationListenerServicePermitted(
4636 systemListener, MANAGED_PROFILE_USER_ID));
4637 assertTrue(dpms.isNotificationListenerServicePermitted(
4638 nonSystemPackage, UserHandle.USER_SYSTEM));
4639 assertTrue(dpms.isNotificationListenerServicePermitted(
4640 systemListener, UserHandle.USER_SYSTEM));
4641
4642 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4643 // all allowed in primary profile
4644 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4645 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004646 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004647 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4648
4649 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4650 assertFalse(dpms.isNotificationListenerServicePermitted(
4651 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4652 assertTrue(dpms.isNotificationListenerServicePermitted(
4653 systemListener, MANAGED_PROFILE_USER_ID));
4654 assertTrue(dpms.isNotificationListenerServicePermitted(
4655 nonSystemPackage, UserHandle.USER_SYSTEM));
4656 assertTrue(dpms.isNotificationListenerServicePermitted(
4657 systemListener, UserHandle.USER_SYSTEM));
4658 }
4659
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004660 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004661 mServiceContext.packageName = mRealTestContext.getPackageName();
4662 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4663 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004664 setDeviceOwner();
4665
Pavel Grafov75c0a892017-05-18 17:28:27 +01004666 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004667 }
4668
4669 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004670 mServiceContext.packageName = mRealTestContext.getPackageName();
4671 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4672 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004673 setAsProfileOwner(admin1);
4674
Pavel Grafov75c0a892017-05-18 17:28:27 +01004675 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4676 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004677 }
4678
4679 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004680 mServiceContext.packageName = mRealTestContext.getPackageName();
4681 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4682 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004683 setAsProfileOwner(admin1);
4684
Pavel Grafov75c0a892017-05-18 17:28:27 +01004685 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4686 caller.packageName = "com.example.delegate";
4687 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4688 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004689
Pavel Grafov75c0a892017-05-18 17:28:27 +01004690 // Make caller a delegated cert installer.
4691 runAsCaller(mAdmin1Context, dpms,
4692 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004693
4694 verifyCanGetOwnerInstalledCaCerts(null, caller);
4695 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004696 }
4697
Rubin Xucc391c22018-01-02 20:37:35 +00004698 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004699 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4700 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004701 Bundle restriction = new Bundle();
4702 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4703
4704 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4705 RestrictionsListener listener = new RestrictionsListener(mContext);
4706 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4707 new Bundle());
4708 verifyDataSharingChangedBroadcast();
4709 }
4710
4711 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004712 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4713 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004714 Bundle restriction = new Bundle();
4715 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4716
4717 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4718 RestrictionsListener listener = new RestrictionsListener(mContext);
4719 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4720 restriction);
4721 verifyDataSharingChangedBroadcast();
4722 }
4723
4724 public void testDisallowSharingIntoProfileUnchanged() {
4725 RestrictionsListener listener = new RestrictionsListener(mContext);
4726 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4727 new Bundle());
4728 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4729 }
4730
4731 private void verifyDataSharingChangedBroadcast() {
4732 Intent expectedIntent = new Intent(
4733 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4734 expectedIntent.setPackage("com.android.managedprovisioning");
4735 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4736 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4737 MockUtils.checkIntent(expectedIntent),
4738 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4739 }
4740
yuemingwe3d9c092018-01-11 12:11:44 +00004741 public void testOverrideApnAPIsFailWithPO() throws Exception {
4742 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004743 ApnSetting apn = (new ApnSetting.Builder())
4744 .setApnName("test")
4745 .setEntryName("test")
4746 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4747 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004748 assertExpectException(SecurityException.class, null, () ->
4749 dpm.addOverrideApn(admin1, apn));
4750 assertExpectException(SecurityException.class, null, () ->
4751 dpm.updateOverrideApn(admin1, 0, apn));
4752 assertExpectException(SecurityException.class, null, () ->
4753 dpm.removeOverrideApn(admin1, 0));
4754 assertExpectException(SecurityException.class, null, () ->
4755 dpm.getOverrideApns(admin1));
4756 assertExpectException(SecurityException.class, null, () ->
4757 dpm.setOverrideApnsEnabled(admin1, false));
4758 assertExpectException(SecurityException.class, null, () ->
4759 dpm.isOverrideApnEnabled(admin1));
4760 }
4761
Robin Lee2c68dad2017-03-17 12:50:24 +00004762 private void verifyCanGetOwnerInstalledCaCerts(
4763 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004764 final String alias = "cert";
4765 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004766
4767 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004768 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004769 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4770 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004771 }
4772 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4773
4774 // caller: device admin or delegated certificate installer
4775 callerContext.applicationInfo = new ApplicationInfo();
4776 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4777
4778 // system_server
4779 final DpmMockContext serviceContext = mContext;
4780 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004781 getServices().addPackageContext(callerUser, admin1Context);
4782 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004783
4784 // Install a CA cert.
4785 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004786 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004787 .thenReturn(alias);
4788 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004789 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004790 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004791 });
4792
Pavel Grafov75c0a892017-05-18 17:28:27 +01004793 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4794 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4795 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004796 flushTasks();
4797
Robin Lee2c68dad2017-03-17 12:50:24 +00004798 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4799
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004800 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004801 runAsCaller(admin1Context, dpms, (dpm) -> {
4802 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004803 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004804 ownerInstalledCaCerts.addAll(installedCaCerts);
4805 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004806
4807 // Restarting the DPMS should not lose information.
4808 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004809 runAsCaller(admin1Context, dpms, (dpm) ->
4810 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004811
4812 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004813 runAsCaller(serviceContext, dpms, (dpm) -> {
4814 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004815
Robin Lee2c68dad2017-03-17 12:50:24 +00004816 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004817 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004818 });
4819
Pavel Grafov75c0a892017-05-18 17:28:27 +01004820 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4821 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4822 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004823 flushTasks();
4824
4825 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4826 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004827 runAsCaller(admin1Context, dpms, (dpm) -> {
4828 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4829 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004830 }
4831
Robin Lee2c68dad2017-03-17 12:50:24 +00004832 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4833 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004834 final String alias = "cert";
4835 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004836
4837 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004838 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004839 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4840 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004841 }
4842 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4843
4844 // caller: device admin or delegated certificate installer
4845 callerContext.applicationInfo = new ApplicationInfo();
4846 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4847
4848 // system_server
4849 final DpmMockContext serviceContext = mContext;
4850 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004851 getServices().addPackageContext(callerUser, admin1Context);
4852 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004853
4854 // Install a CA cert as caller
4855 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004856 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004857 .thenReturn(alias);
4858 assertTrue(dpm.installCaCert(callerName, caCert));
4859 });
4860
4861 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004862 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004863 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004864 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4865 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4866 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004867 flushTasks();
4868
Robin Lee2c68dad2017-03-17 12:50:24 +00004869 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004870 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004871
4872 runAsCaller(serviceContext, dpms, (dpm) -> {
4873 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4874 assertNotNull(ownerInstalledCaCerts);
4875 assertTrue(ownerInstalledCaCerts.isEmpty());
4876 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004877 }
4878
Eran Messeri94d56762017-12-21 20:50:54 +00004879 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4880 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4881 Arrays.sort(gotFlags);
4882 Arrays.sort(expectedFlags);
4883 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4884 }
4885
4886 public void testTranslationOfIdAttestationFlag() {
4887 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4888 int[] correspondingAttUtilsTypes = new int[]{
4889 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4890 AttestationUtils.ID_TYPE_MEID};
4891
4892 // Test translation of zero flags
4893 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4894
4895 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4896 // non-null array
4897 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4898
4899 // Test translation of a single flag
4900 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4901 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4902 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4903
4904 // Test translation of two flags
4905 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4906 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4907 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4908 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4909
4910 // Test translation of all three flags
4911 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4912 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4913 AttestationUtils.ID_TYPE_MEID});
4914 // Test translation of all three flags
4915 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4916 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4917 AttestationUtils.ID_TYPE_MEID});
4918 }
4919
arangelov08d534b2018-01-22 15:20:53 +00004920 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4921 setDeviceOwner();
4922 initializeDpms();
4923 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4924 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4925 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4926 }
4927
4928 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4929 DpmTestUtils.writeInputStreamToFile(
4930 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4931 getDeviceOwnerPoliciesFile());
4932 DpmTestUtils.writeInputStreamToFile(
4933 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4934 getDeviceOwnerFile());
4935 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4936 }
4937
4938 public void testRevertDeviceOwnership_deviceNotMigrated()
4939 throws Exception {
4940 DpmTestUtils.writeInputStreamToFile(
4941 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4942 getDeviceOwnerPoliciesFile());
4943 DpmTestUtils.writeInputStreamToFile(
4944 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4945 getDeviceOwnerFile());
4946 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4947 }
4948
4949 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4950 throws Exception {
4951 DpmTestUtils.writeInputStreamToFile(
4952 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4953 getDeviceOwnerPoliciesFile());
4954 DpmTestUtils.writeInputStreamToFile(
4955 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4956 getDeviceOwnerFile());
4957 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4958 }
4959
4960 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4961 setupProfileOwner();
4962 initializeDpms();
4963 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4964 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4965 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4966 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4967 }
4968
4969 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4970 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4971 UserHandle.USER_SYSTEM);
4972 DpmTestUtils.writeInputStreamToFile(
4973 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4974 getProfileOwnerPoliciesFile());
4975 DpmTestUtils.writeInputStreamToFile(
4976 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4977 getProfileOwnerFile());
4978 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4979 }
4980
4981 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4982 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4983 UserHandle.USER_SYSTEM);
4984 DpmTestUtils.writeInputStreamToFile(
4985 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4986 getProfileOwnerPoliciesFile());
4987 DpmTestUtils.writeInputStreamToFile(
4988 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4989 getProfileOwnerFile());
4990 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4991 }
4992
4993 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
4994 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4995 UserHandle.USER_SYSTEM);
4996 DpmTestUtils.writeInputStreamToFile(
4997 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4998 getProfileOwnerPoliciesFile());
4999 DpmTestUtils.writeInputStreamToFile(
5000 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5001 getProfileOwnerFile());
5002 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5003 }
5004
5005 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5006 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5007 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5008 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5009
5010 final long ident = mServiceContext.binder.clearCallingIdentity();
5011 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5012 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5013 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5014 // To simulate a reboot, we just reinitialize dpms and call systemReady
5015 initializeDpms();
5016
5017 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5018 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5019 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5020 assertTrue(dpm.isAdminActive(admin1));
5021 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5022 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5023
5024 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5025 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5026 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5027 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5028
5029 mServiceContext.binder.restoreCallingIdentity(ident);
5030 }
5031
5032 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5033 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5034 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5035 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5036
5037 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5038 DpmMockContext.CALLER_SYSTEM_USER_UID);
5039 setUpPackageManagerForAdmin(admin1, uid);
5040 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5041 // To simulate a reboot, we just reinitialize dpms and call systemReady
5042 initializeDpms();
5043
5044 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5045 assertTrue(dpm.isAdminActive(admin1));
5046 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5047 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5048 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5049 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5050 }
5051
5052 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5053 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5054 metadataManager.deleteMetadataFile();
5055
5056 final TransferOwnershipMetadataManager.Metadata metadata =
5057 new TransferOwnershipMetadataManager.Metadata(
5058 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5059 callerUserHandle,
5060 adminType);
5061 metadataManager.saveMetadataFile(metadata);
5062 }
5063
5064 private File getDeviceOwnerFile() {
5065 return dpms.mOwners.getDeviceOwnerFile();
5066 }
5067
5068 private File getProfileOwnerFile() {
5069 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5070 }
5071
5072 private File getProfileOwnerPoliciesFile() {
5073 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5074 DpmMockContext.CALLER_USER_HANDLE);
5075 return getPoliciesFile(parentDir);
5076 }
5077
5078 private File getDeviceOwnerPoliciesFile() {
5079 return getPoliciesFile(getServices().systemUserDataDir);
5080 }
5081
5082 private File getPoliciesFile(File parentDir) {
5083 return new File(parentDir, "device_policies.xml");
5084 }
5085
5086 private InputStream getRawStream(@RawRes int id) {
5087 return mRealTestContext.getResources().openRawResource(id);
5088 }
5089
Victor Chang3e794af2016-03-04 13:48:17 +00005090 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005091 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005092 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5093 dpms.notifyChangeToContentObserver(
5094 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5095 }
5096
5097 private void assertProvisioningAllowed(String action, boolean expected) {
5098 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5099 dpm.isProvisioningAllowed(action));
5100 }
Tony Mak2f26b792016-11-28 17:54:51 +00005101
Nicolas Prevot45d29072017-01-18 16:11:19 +00005102 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5103 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005104 final String previousPackageName = mContext.packageName;
5105 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005106
5107 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5108 mContext.packageName = packageName;
5109 mMockContext.binder.callingUid = uid;
5110 assertProvisioningAllowed(action, expected);
5111
5112 // Set the previous package name / calling uid to go back to the initial state.
5113 mContext.packageName = previousPackageName;
5114 mMockContext.binder.callingUid = previousUid;
5115 }
5116
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005117 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005118 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5119 }
5120
5121 private void assertCheckProvisioningPreCondition(
5122 String action, String packageName, int provisioningCondition) {
5123 assertEquals("checkProvisioningPreCondition("
5124 + action + ", " + packageName + ") returning unexpected result",
5125 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005126 }
5127
Tony Mak2f26b792016-11-28 17:54:51 +00005128 /**
5129 * Setup a managed profile with the specified admin and its uid.
5130 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5131 * @param adminUid uid of the admin package.
5132 * @param copyFromAdmin package information for {@code admin} will be built based on this
5133 * component's information.
5134 */
5135 private void addManagedProfile(
5136 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5137 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005138 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005139 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5140 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5141 dpm.setActiveAdmin(admin, false, userId);
5142 assertTrue(dpm.setProfileOwner(admin, null, userId));
5143 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5144 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005145
5146 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005147 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005148 */
Robin Leeabaa0692017-02-20 20:54:22 +00005149 private static StringParceledListSlice asSlice(String[] s) {
5150 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005151 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005152
5153 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005154 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5155 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005156
Robin Lee2c68dad2017-03-17 12:50:24 +00005157 // We can't let exceptions happen on the background thread. Throw them here if they happen
5158 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005159 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005160 }
Victor Chang3e794af2016-03-04 13:48:17 +00005161}