blob: cbabb0b350d19a066e641cf71af0379d96b904c5 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010028import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
29import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
30import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
31
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Pavel Grafov75c0a892017-05-18 17:28:27 +010035import static org.mockito.Matchers.any;
36import static org.mockito.Matchers.anyInt;
37import static org.mockito.Matchers.anyLong;
38import static org.mockito.Matchers.anyObject;
39import static org.mockito.Matchers.anyString;
40import static org.mockito.Matchers.eq;
41import static org.mockito.Matchers.isNull;
42import static org.mockito.Mockito.atLeast;
43import static org.mockito.Mockito.doAnswer;
44import static org.mockito.Mockito.doReturn;
45import static org.mockito.Mockito.never;
46import static org.mockito.Mockito.nullable;
47import static org.mockito.Mockito.reset;
48import static org.mockito.Mockito.timeout;
49import static org.mockito.Mockito.times;
50import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080051import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010052import static org.mockito.Mockito.verifyZeroInteractions;
53import static org.mockito.Mockito.when;
54import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000055import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056
Makoto Onukif76b06a2015-09-22 15:03:44 -070057import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000058import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000060import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070061import android.app.admin.DeviceAdminReceiver;
62import android.app.admin.DevicePolicyManager;
63import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010064import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070065import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070066import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000067import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000068import android.content.pm.ApplicationInfo;
69import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010071import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000072import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000073import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010074import android.graphics.Color;
75import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080076import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070077import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080078import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070079import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070080import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010081import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080082import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010083import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000084import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000085import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000086import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080087import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010088import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070089import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070090
Pavel Grafov57f1b662019-03-27 14:55:38 +000091import androidx.test.filters.SmallTest;
92
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010093import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000094import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000095import com.android.server.LocalServices;
96import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000097import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000098import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000099
Robin Lee7f5c91c2017-02-08 21:27:02 +0000100import org.hamcrest.BaseMatcher;
101import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800102import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700103import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104
arangelov08d534b2018-01-22 15:20:53 +0000105import java.io.File;
106import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800107import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000108import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000109import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700110import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700112import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100113import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000114import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700117 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000118 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119 m FrameworksServicesTests &&
120 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000121 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700123 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124
125 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000126 *
127 * , or:
128 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000130@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100131@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700132public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000133 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
134 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
135 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100136 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800137 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100138 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000139
Pavel Grafov75c0a892017-05-18 17:28:27 +0100140 // TODO replace all instances of this with explicit {@link #mServiceContext}.
141 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700142 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100143
144 private DpmMockContext mServiceContext;
145 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700146 public DevicePolicyManager dpm;
147 public DevicePolicyManagerServiceTestable dpms;
148
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100149 /*
150 * The CA cert below is the content of cacert.pem as generated by:
151 *
152 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
153 */
154 private static final String TEST_CA =
155 "-----BEGIN CERTIFICATE-----\n" +
156 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
157 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
158 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
159 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
160 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
161 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
162 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
163 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
164 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
165 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
166 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
167 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
168 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
169 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
170 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
171 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
172 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
173 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
174 "wQ==\n" +
175 "-----END CERTIFICATE-----\n";
176
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700177 @Override
178 protected void setUp() throws Exception {
179 super.setUp();
180
181 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100182 mServiceContext = mContext;
183 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
184 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700185 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100186 doReturn(Collections.singletonList(new ResolveInfo()))
187 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
188 any(Intent.class),
189 anyInt(),
190 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700191
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800192 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100193 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800194
Makoto Onukia52562c2015-10-01 16:12:31 -0700195 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700196
Sudheer Shanka101c3532018-01-08 16:28:42 -0800197 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800198 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700199 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
200 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
201 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800202 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700203
Pavel Grafov75c0a892017-05-18 17:28:27 +0100204 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
205 mAdmin1Context.packageName = admin1.getPackageName();
206 mAdmin1Context.applicationInfo = new ApplicationInfo();
207 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
208
Makoto Onukib643fb02015-09-22 15:03:44 -0700209 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100210
211 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700212 }
213
arangelov08d534b2018-01-22 15:20:53 +0000214 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
215 return dpms.mTransferOwnershipMetadataManager;
216 }
217
Robin Lee2c68dad2017-03-17 12:50:24 +0000218 @Override
219 protected void tearDown() throws Exception {
220 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000221 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000222 super.tearDown();
223 }
224
Makoto Onukia52562c2015-10-01 16:12:31 -0700225 private void initializeDpms() {
226 // Need clearCallingIdentity() to pass permission checks.
227 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100228 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700229
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
231 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
232 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700233
Pavel Grafov75c0a892017-05-18 17:28:27 +0100234 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237 }
238
Makoto Onukib643fb02015-09-22 15:03:44 -0700239 private void setUpUserManager() {
240 // Emulate UserManager.set/getApplicationRestriction().
241 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
242
243 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000244 doAnswer((Answer<Void>) invocation -> {
245 String pkg = (String) invocation.getArguments()[0];
246 Bundle bundle = (Bundle) invocation.getArguments()[1];
247 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700248
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000249 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000251 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100252 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100253 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700254
255 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000256 doAnswer((Answer<Bundle>) invocation -> {
257 String pkg = (String) invocation.getArguments()[0];
258 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700259
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000260 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100261 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700262 anyString(), any(UserHandle.class));
263
Makoto Onukid932f762015-09-29 16:53:38 -0700264 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700266 }
267
268 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100269 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700270
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 mServiceContext.binder.callingUid =
272 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
273 runAsCaller(mServiceContext, dpms, dpm -> {
274 // PO needs to be a DA.
275 dpm.setActiveAdmin(admin, /*replace=*/ false);
276 // Fire!
277 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
278 // Check
279 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
280 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700281
Pavel Grafov75c0a892017-05-18 17:28:27 +0100282 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700283 }
284
285 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100286 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700287 .thenReturn(false);
288
289 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100290 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700291
292 // If the device has no DPMS feature, it shouldn't register the local service.
293 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
294 }
295
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800296 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800297 // Device owner in SYSTEM_USER
298 setDeviceOwner();
299 // Profile owner in CALLER_USER_HANDLE
300 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
301 setAsProfileOwner(admin2);
302 // Active admin in CALLER_USER_HANDLE
303 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
304 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
305 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
306 DpmMockContext.CALLER_USER_HANDLE);
307 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
308 DpmMockContext.CALLER_USER_HANDLE));
309
310 initializeDpms();
311
312 // Verify
313 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800314 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800315 eq(UserHandle.USER_SYSTEM));
316 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800317 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800318 adminAnotherPackage.getPackageName()),
319 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800320 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
321 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
322 }
323
324 public void testLoadAdminData_noAdmins() throws Exception {
325 final int ANOTHER_USER_ID = 15;
326 getServices().addUser(ANOTHER_USER_ID, 0);
327
328 initializeDpms();
329
330 // Verify
331 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
332 null, DpmMockContext.CALLER_USER_HANDLE);
333 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
334 null, ANOTHER_USER_ID);
335 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
336 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800337 }
338
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700339 /**
340 * Caller doesn't have proper permissions.
341 */
342 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700343 // 1. Failure cases.
344
345 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100346 assertExpectException(SecurityException.class, /* messageRegex= */ null,
347 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700348
349 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
350 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100351
352 assertExpectException(SecurityException.class, /* messageRegex= */ null,
353 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700354 }
355
Makoto Onukif76b06a2015-09-22 15:03:44 -0700356 /**
357 * Test for:
358 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800359 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700360 * {@link DevicePolicyManager#isAdminActive}
361 * {@link DevicePolicyManager#isAdminActiveAsUser}
362 * {@link DevicePolicyManager#getActiveAdmins}
363 * {@link DevicePolicyManager#getActiveAdminsAsUser}
364 */
365 public void testSetActiveAdmin() throws Exception {
366 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700367 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
368
Makoto Onukif76b06a2015-09-22 15:03:44 -0700369 // 2. Call the API.
370 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700371
372 // 3. Verify internal calls.
373
374 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700375 verify(mContext.spiedContext).sendBroadcastAsUser(
376 MockUtils.checkIntentAction(
377 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
378 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
379 verify(mContext.spiedContext).sendBroadcastAsUser(
380 MockUtils.checkIntentAction(
381 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700382 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
383
Pavel Grafov75c0a892017-05-18 17:28:27 +0100384 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700385 eq(admin1.getPackageName()),
386 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
387 eq(PackageManager.DONT_KILL_APP),
388 eq(DpmMockContext.CALLER_USER_HANDLE),
389 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700390
Sudheer Shanka101c3532018-01-08 16:28:42 -0800391 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
392 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
393
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700395
396 // Make sure it's active admin1.
397 assertTrue(dpm.isAdminActive(admin1));
398 assertFalse(dpm.isAdminActive(admin2));
399 assertFalse(dpm.isAdminActive(admin3));
400
401 // But not admin1 for a different user.
402
403 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
404 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
405 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
406
407 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
408 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
409
410 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
411
412 // Next, add one more admin.
413 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700414 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700415 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700416
417 dpm.setActiveAdmin(admin2, /* replace =*/ false);
418
419 // Now we have two admins.
420 assertTrue(dpm.isAdminActive(admin1));
421 assertTrue(dpm.isAdminActive(admin2));
422 assertFalse(dpm.isAdminActive(admin3));
423
424 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
425 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100426 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700427 eq(admin1.getPackageName()),
428 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
429 eq(PackageManager.DONT_KILL_APP),
430 eq(DpmMockContext.CALLER_USER_HANDLE),
431 anyString());
432
Sudheer Shanka101c3532018-01-08 16:28:42 -0800433 // times(2) because it was previously called for admin1 which is in the same package
434 // as admin2.
435 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
436 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
437
Makoto Onukif76b06a2015-09-22 15:03:44 -0700438 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100439 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
440 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700441
442 // 5. Add the same admin1 again with replace, which should succeed.
443 dpm.setActiveAdmin(admin1, /* replace =*/ true);
444
445 // TODO make sure it's replaced.
446
447 // 6. Test getActiveAdmins()
448 List<ComponentName> admins = dpm.getActiveAdmins();
449 assertEquals(2, admins.size());
450 assertEquals(admin1, admins.get(0));
451 assertEquals(admin2, admins.get(1));
452
Sudheer Shanka101c3532018-01-08 16:28:42 -0800453 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
454 // replaced
455 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
456
Makoto Onukif76b06a2015-09-22 15:03:44 -0700457 // Another user has no admins.
458 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
459
460 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
461 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
462
463 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
464 }
465
Makoto Onukid932f762015-09-29 16:53:38 -0700466 public void testSetActiveAdmin_multiUsers() throws Exception {
467
468 final int ANOTHER_USER_ID = 100;
469 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
470
Pavel Grafov75c0a892017-05-18 17:28:27 +0100471 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700472
473 // Set up pacakge manager for the other user.
474 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700475
476 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
477
478 dpm.setActiveAdmin(admin1, /* replace =*/ false);
479
480 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
481 dpm.setActiveAdmin(admin2, /* replace =*/ false);
482
483
484 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
485 assertTrue(dpm.isAdminActive(admin1));
486 assertFalse(dpm.isAdminActive(admin2));
487
488 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
489 assertFalse(dpm.isAdminActive(admin1));
490 assertTrue(dpm.isAdminActive(admin2));
491 }
492
Makoto Onukif76b06a2015-09-22 15:03:44 -0700493 /**
494 * Test for:
495 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800496 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 */
498 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
499 // 1. Make sure the caller has proper permissions.
500 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
501
502 dpm.setActiveAdmin(admin1, /* replace =*/ false);
503 assertTrue(dpm.isAdminActive(admin1));
504
505 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100506 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
507 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700508 }
509
510 /**
511 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800512 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
513 * BIND_DEVICE_ADMIN.
514 */
515 public void testSetActiveAdmin_permissionCheck() throws Exception {
516 // 1. Make sure the caller has proper permissions.
517 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
518
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100519 assertExpectException(IllegalArgumentException.class,
520 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
521 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800522 assertFalse(dpm.isAdminActive(adminNoPerm));
523
524 // Change the target API level to MNC. Now it can be set as DA.
525 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
526 VERSION_CODES.M);
527 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
528 assertTrue(dpm.isAdminActive(adminNoPerm));
529
530 // TODO Test the "load from the file" case where DA will still be loaded even without
531 // BIND_DEVICE_ADMIN and target API is N.
532 }
533
534 /**
535 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 * {@link DevicePolicyManager#removeActiveAdmin}
537 */
538 public void testRemoveActiveAdmin_SecurityException() {
539 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
540
541 // Add admin.
542
543 dpm.setActiveAdmin(admin1, /* replace =*/ false);
544
545 assertTrue(dpm.isAdminActive(admin1));
546
547 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
548
549 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100550 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
551 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700552
553 // Try to remove active admin with a different caller userid should fail too, without
554 // having MANAGE_DEVICE_ADMINS.
555 mContext.callerPermissions.clear();
556
Makoto Onukid932f762015-09-29 16:53:38 -0700557 // Change the caller, and call into DPMS directly with a different user-id.
558
Makoto Onukif76b06a2015-09-22 15:03:44 -0700559 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100560 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
561 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700562 }
563
564 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800565 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
566 * (because we can't send the remove broadcast).
567 */
568 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
569 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
570
571 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
572
573 // Add admin.
574
575 dpm.setActiveAdmin(admin1, /* replace =*/ false);
576
577 assertTrue(dpm.isAdminActive(admin1));
578
579 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
580
581 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100582 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800583 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100584 assertExpectException(IllegalStateException.class,
585 /* messageRegex= */ "User must be running and unlocked",
586 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587
588 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800589 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
590 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100593 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800594 .thenReturn(true);
595
596 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700597 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800598 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
599 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800600 }
601
602 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700603 * Test for:
604 * {@link DevicePolicyManager#removeActiveAdmin}
605 */
Makoto Onukid932f762015-09-29 16:53:38 -0700606 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
608
609 // Add admin1.
610
611 dpm.setActiveAdmin(admin1, /* replace =*/ false);
612
613 assertTrue(dpm.isAdminActive(admin1));
614 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
615
616 // Different user, but should work, because caller has proper permissions.
617 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700618
619 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700620 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700621
622 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700623 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800624 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
625 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700626
627 // TODO DO Still can't be removed in this case.
628 }
629
630 /**
631 * Test for:
632 * {@link DevicePolicyManager#removeActiveAdmin}
633 */
634 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
635 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
636 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
637
638 // Add admin1.
639
640 dpm.setActiveAdmin(admin1, /* replace =*/ false);
641
642 assertTrue(dpm.isAdminActive(admin1));
643 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
644
645 // Broadcast from saveSettingsLocked().
646 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
647 MockUtils.checkIntentAction(
648 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
649 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
650
651 // Remove. No permissions, but same user, so it'll work.
652 mContext.callerPermissions.clear();
653 dpm.removeActiveAdmin(admin1);
654
Makoto Onukif76b06a2015-09-22 15:03:44 -0700655 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
656 MockUtils.checkIntentAction(
657 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
658 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
659 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700660 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700661 eq(dpms.mHandler),
662 eq(Activity.RESULT_OK),
663 isNull(String.class),
664 isNull(Bundle.class));
665
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800667 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
668 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700669
670 // Again broadcast from saveSettingsLocked().
671 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
672 MockUtils.checkIntentAction(
673 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
674 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
675
676 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700677 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700678
Sudheer Shanka101c3532018-01-08 16:28:42 -0800679 public void testRemoveActiveAdmin_multipleAdminsInUser() {
680 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
681 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
682
683 // Add admin1.
684 dpm.setActiveAdmin(admin1, /* replace =*/ false);
685
686 assertTrue(dpm.isAdminActive(admin1));
687 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
688
689 // Add admin2.
690 dpm.setActiveAdmin(admin2, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin2));
693 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Broadcast from saveSettingsLocked().
696 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
697 MockUtils.checkIntentAction(
698 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
699 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
700
701 // Remove. No permissions, but same user, so it'll work.
702 mContext.callerPermissions.clear();
703 dpm.removeActiveAdmin(admin1);
704
705 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
706 MockUtils.checkIntentAction(
707 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
708 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
709 isNull(String.class),
710 any(BroadcastReceiver.class),
711 eq(dpms.mHandler),
712 eq(Activity.RESULT_OK),
713 isNull(String.class),
714 isNull(Bundle.class));
715
716 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
717 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800718 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800719 eq(DpmMockContext.CALLER_USER_HANDLE));
720
721 // Again broadcast from saveSettingsLocked().
722 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
723 MockUtils.checkIntentAction(
724 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
725 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
726 }
727
728 /**
729 * Test for:
730 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
731 */
732 public void testForceRemoveActiveAdmin() throws Exception {
733 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
734
735 // Add admin.
736 setupPackageInPackageManager(admin1.getPackageName(),
737 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
738 /* appId= */ 10138,
739 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
740 dpm.setActiveAdmin(admin1, /* replace =*/ false);
741 assertTrue(dpm.isAdminActive(admin1));
742
743 // Calling from a non-shell uid should fail with a SecurityException
744 mContext.binder.callingUid = 123456;
745 assertExpectException(SecurityException.class,
746 /* messageRegex =*/ "Non-shell user attempted to call",
747 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
748
749 mContext.binder.callingUid = Process.SHELL_UID;
750 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
751
752 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
753 // Verify
754 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
755 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
756 null, DpmMockContext.CALLER_USER_HANDLE);
757 }
758
Makoto Onukib643fb02015-09-22 15:03:44 -0700759 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000760 * Test for: @{link DevicePolicyManager#setActivePasswordState}
761 *
762 * Validates that when the password for a user changes, the notification broadcast intent
763 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
764 * addition to ones in the original user.
765 */
766 public void testSetActivePasswordState_sendToProfiles() throws Exception {
767 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
768
769 final int MANAGED_PROFILE_USER_ID = 78;
770 final int MANAGED_PROFILE_ADMIN_UID =
771 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
772
773 // Setup device owner.
774 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
775 mContext.packageName = admin1.getPackageName();
776 setupDeviceOwner();
777
778 // Add a managed profile belonging to the system user.
779 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
780
781 // Change the parent user's password.
782 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
783
784 // Both the device owner and the managed profile owner should receive this broadcast.
785 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
786 intent.setComponent(admin1);
787 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
788
789 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
790 MockUtils.checkIntent(intent),
791 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
792 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
793 MockUtils.checkIntent(intent),
794 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
795 }
796
797 /**
798 * Test for: @{link DevicePolicyManager#setActivePasswordState}
799 *
800 * Validates that when the password for a managed profile changes, the notification broadcast
801 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
802 * its parent.
803 */
804 public void testSetActivePasswordState_notSentToParent() throws Exception {
805 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
806
807 final int MANAGED_PROFILE_USER_ID = 78;
808 final int MANAGED_PROFILE_ADMIN_UID =
809 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
810
811 // Setup device owner.
812 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
813 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100814 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000815 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
816 setupDeviceOwner();
817
818 // Add a managed profile belonging to the system user.
819 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
820
821 // Change the profile's password.
822 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
823
824 // Both the device owner and the managed profile owner should receive this broadcast.
825 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
826 intent.setComponent(admin1);
827 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
828
829 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
830 MockUtils.checkIntent(intent),
831 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
832 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
833 MockUtils.checkIntent(intent),
834 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
835 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100836
Robin Leed2a73ed2016-12-19 09:07:16 +0000837 /**
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
xshu425b9a62018-12-13 14:18:18 -08001989 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001990 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001991
xshu425b9a62018-12-13 14:18:18 -08001992 // 4-2. When WifiManager returns an empty array, dpm should also output null.
1993 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
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.
xshu425b9a62018-12-13 14:18:18 -08001997 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
1998 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001999 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002000 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002001
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002002 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002003 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2004 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2005
2006 // In this test, change the caller user to "system".
2007 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2008
2009 // Make sure admin1 is installed on system user.
2010 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2011
2012 // Set admin1 as DA.
2013 dpm.setActiveAdmin(admin1, false);
2014 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002015 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2016 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002017
2018 // Set admin1 as PO.
2019 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002020 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2021 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002022
2023 // Remove PO and add DO.
2024 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002025 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002026 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2027
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002028 // admin1 is DO.
2029 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002030 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002031 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002032 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2033 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002034
2035 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002036 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002037 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002038 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2039 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002040
2041 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002042 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002043 dpm.reboot(admin1);
2044 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002045
2046 public void testSetGetSupportText() {
2047 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2048 dpm.setActiveAdmin(admin1, true);
2049 dpm.setActiveAdmin(admin2, true);
2050 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2051
2052 // Null default support messages.
2053 {
2054 assertNull(dpm.getLongSupportMessage(admin1));
2055 assertNull(dpm.getShortSupportMessage(admin1));
2056 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2057 assertNull(dpm.getShortSupportMessageForUser(admin1,
2058 DpmMockContext.CALLER_USER_HANDLE));
2059 assertNull(dpm.getLongSupportMessageForUser(admin1,
2060 DpmMockContext.CALLER_USER_HANDLE));
2061 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2062 }
2063
2064 // Only system can call the per user versions.
2065 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002066 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2067 () -> dpm.getShortSupportMessageForUser(admin1,
2068 DpmMockContext.CALLER_USER_HANDLE));
2069 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2070 () -> dpm.getLongSupportMessageForUser(admin1,
2071 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002072 }
2073
2074 // Can't set message for admin in another uid.
2075 {
2076 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002077 assertExpectException(SecurityException.class,
2078 /* messageRegex= */ "is not owned by uid",
2079 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002080 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2081 }
2082
2083 // Set/Get short returns what it sets and other admins text isn't changed.
2084 {
2085 final String supportText = "Some text to test with.";
2086 dpm.setShortSupportMessage(admin1, supportText);
2087 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2088 assertNull(dpm.getLongSupportMessage(admin1));
2089 assertNull(dpm.getShortSupportMessage(admin2));
2090
2091 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2092 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2093 DpmMockContext.CALLER_USER_HANDLE));
2094 assertNull(dpm.getShortSupportMessageForUser(admin2,
2095 DpmMockContext.CALLER_USER_HANDLE));
2096 assertNull(dpm.getLongSupportMessageForUser(admin1,
2097 DpmMockContext.CALLER_USER_HANDLE));
2098 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2099
2100 dpm.setShortSupportMessage(admin1, null);
2101 assertNull(dpm.getShortSupportMessage(admin1));
2102 }
2103
2104 // Set/Get long returns what it sets and other admins text isn't changed.
2105 {
2106 final String supportText = "Some text to test with.\nWith more text.";
2107 dpm.setLongSupportMessage(admin1, supportText);
2108 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2109 assertNull(dpm.getShortSupportMessage(admin1));
2110 assertNull(dpm.getLongSupportMessage(admin2));
2111
2112 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2113 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2114 DpmMockContext.CALLER_USER_HANDLE));
2115 assertNull(dpm.getLongSupportMessageForUser(admin2,
2116 DpmMockContext.CALLER_USER_HANDLE));
2117 assertNull(dpm.getShortSupportMessageForUser(admin1,
2118 DpmMockContext.CALLER_USER_HANDLE));
2119 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2120
2121 dpm.setLongSupportMessage(admin1, null);
2122 assertNull(dpm.getLongSupportMessage(admin1));
2123 }
2124 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002125
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002126 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002127 setAsProfileOwner(admin1);
2128
2129 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002130 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002131
2132 // Setup
2133 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2134 final String package1 = "com.example.one";
2135 final String package2 = "com.example.two";
2136 pkgsToRestrict.add(package1);
2137 pkgsToRestrict.add(package2);
2138 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2139 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002140 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002141
2142 // Verify
2143 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002144 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002145 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2146 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2147 eq(DpmMockContext.CALLER_USER_HANDLE));
2148
2149 // Setup
2150 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002151 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002152
2153 // Verify
2154 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002155 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002156 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2157 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2158 eq(DpmMockContext.CALLER_USER_HANDLE));
2159 }
2160
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002161 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002162 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2163 dpm.setActiveAdmin(admin1, true);
2164 assertTrue(dpm.isAdminActive(admin1));
2165 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2166
2167 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002168 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002169 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002170 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002171 }
2172
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002173 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002174 setAsProfileOwner(admin1);
2175
2176 // Setup
2177 final ArrayList<String> emptyList = new ArrayList<>();
2178 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2179 final String package1 = "com.example.one";
2180 final String package2 = "com.example.two";
2181 final String package3 = "com.example.three";
2182 pkgsToRestrict.add(package1);
2183 pkgsToRestrict.add(package2);
2184 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2185 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002186 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002187
2188 // Verify
2189 assertEquals(emptyList, excludedPkgs);
2190 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2191 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002192 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002193 DpmMockContext.CALLER_USER_HANDLE));
2194 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002195 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002196 DpmMockContext.CALLER_USER_HANDLE));
2197 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002198 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002199 DpmMockContext.CALLER_USER_HANDLE));
2200 }
2201
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002203 setAsProfileOwner(admin1);
2204 assertExpectException(SecurityException.class,
2205 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002206 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002207 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2208 dpm.clearProfileOwner(admin1);
2209
2210 setDeviceOwner();
2211 assertExpectException(SecurityException.class,
2212 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002213 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002214 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2215 clearDeviceOwner();
2216 }
2217
phweiss73145f42017-01-17 19:06:38 +01002218 public void testCreateAdminSupportIntent() throws Exception {
2219 // Setup device owner.
2220 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2221 setupDeviceOwner();
2222
2223 // Nonexisting permission returns null
2224 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2225 assertNull(intent);
2226
2227 // Existing permission that is not set returns null
2228 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2229 assertNull(intent);
2230
2231 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002232 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002233 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2234 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2235 .thenReturn(true);
2236 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2237 assertNull(intent);
2238
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002239 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2240 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2241 new UserManager.EnforcingUser(
2242 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2243 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002244 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002245 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002246 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2247 assertNotNull(intent);
2248 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2249 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2250 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002251 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002252 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2253 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2254
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002255 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2256 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002257
2258 // Camera is not disabled
2259 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2260 assertNull(intent);
2261
2262 // Camera is disabled
2263 dpm.setCameraDisabled(admin1, true);
2264 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2265 assertNotNull(intent);
2266 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2267 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2268
2269 // Screen capture is not disabled
2270 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2271 assertNull(intent);
2272
2273 // Screen capture is disabled
2274 dpm.setScreenCaptureDisabled(admin1, true);
2275 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2276 assertNotNull(intent);
2277 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2278 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2279
2280 // Same checks for different user
2281 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2282 // Camera should be disabled by device owner
2283 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2284 assertNotNull(intent);
2285 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2286 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2287 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2288 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2289 // ScreenCapture should not be disabled by device owner
2290 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2291 assertNull(intent);
2292 }
2293
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002294 /**
2295 * Test for:
2296 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002297 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002298 * {@link DevicePolicyManager#isAffiliatedUser}
2299 */
2300 public void testUserAffiliation() throws Exception {
2301 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2302 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2303 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2304
2305 // Check that the system user is unaffiliated.
2306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2307 assertFalse(dpm.isAffiliatedUser());
2308
2309 // Set a device owner on the system user. Check that the system user becomes affiliated.
2310 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2311 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2312 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2313 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002314 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002315
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002316 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002317 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2318 setAsProfileOwner(admin2);
2319 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002320 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002321
2322 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2323 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002324 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002325 userAffiliationIds.add("red");
2326 userAffiliationIds.add("green");
2327 userAffiliationIds.add("blue");
2328 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002329 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002330 assertFalse(dpm.isAffiliatedUser());
2331
2332 // Have the device owner specify a set of affiliation ids that do not intersect with those
2333 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002334 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002335 deviceAffiliationIds.add("cyan");
2336 deviceAffiliationIds.add("yellow");
2337 deviceAffiliationIds.add("magenta");
2338 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2339 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002340 MoreAsserts.assertContentsInAnyOrder(
2341 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002342 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2343 assertFalse(dpm.isAffiliatedUser());
2344
2345 // Have the profile owner specify a set of affiliation ids that intersect with those
2346 // specified by the device owner. Check that the test user becomes affiliated.
2347 userAffiliationIds.add("yellow");
2348 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002349 MoreAsserts.assertContentsInAnyOrder(
2350 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002351 assertTrue(dpm.isAffiliatedUser());
2352
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002353 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002354 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002355 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002356 assertFalse(dpm.isAffiliatedUser());
2357
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002358 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2359 dpm.setAffiliationIds(admin2, userAffiliationIds);
2360 assertTrue(dpm.isAffiliatedUser());
2361 dpm.clearProfileOwner(admin2);
2362 assertFalse(dpm.isAffiliatedUser());
2363
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002364 // Check that the system user remains affiliated.
2365 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2366 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002367
2368 // Clear the device owner - the user becomes unaffiliated.
2369 clearDeviceOwner();
2370 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002371 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002372
2373 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002374 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002375 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2376 }
2377
2378 public void testSetUserProvisioningState_permission() throws Exception {
2379 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002380
2381 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2382 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2383 }
2384
2385 public void testSetUserProvisioningState_unprivileged() throws Exception {
2386 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002387 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2388 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2389 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002390 }
2391
2392 public void testSetUserProvisioningState_noManagement() {
2393 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002394 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002395 assertExpectException(IllegalStateException.class,
2396 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2397 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2398 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002399 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2400 }
2401
2402 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2403 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2404 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002405
2406 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2407 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2408 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2409 }
2410
2411 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2412 throws Exception {
2413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2414 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002415
2416 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2417 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2418 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2419 }
2420
2421 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2422 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2423 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002424
2425 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2426 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2427 }
2428
2429 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2430 throws Exception {
2431 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002432
2433 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2434 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2435 DevicePolicyManager.STATE_USER_UNMANAGED);
2436 }
2437
2438 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2439 throws Exception {
2440 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002441
2442 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2443 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2444 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2445 }
2446
2447 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2448 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002449
2450 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2451 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2452 }
2453
2454 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2455 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002456
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002457 assertExpectException(IllegalStateException.class,
2458 /* messageRegex= */ "Cannot move to user provisioning state",
2459 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2460 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2461 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002462 }
2463
2464 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2465 throws Exception {
2466 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002467
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002468 assertExpectException(IllegalStateException.class,
2469 /* messageRegex= */ "Cannot move to user provisioning state",
2470 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2471 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2472 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002473 }
2474
2475 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002476 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2477 mContext.callerPermissions.add(permission.MANAGE_USERS);
2478
Alan Treadwayafad8782016-01-19 15:15:08 +00002479 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2480 for (int state : states) {
2481 dpm.setUserProvisioningState(state, userId);
2482 assertEquals(state, dpm.getUserProvisioningState());
2483 }
2484 }
2485
2486 private void setupProfileOwner() throws Exception {
2487 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2488
2489 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2490 dpm.setActiveAdmin(admin1, false);
2491 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2492
2493 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2494 }
2495
2496 private void setupDeviceOwner() throws Exception {
2497 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2498
2499 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2500 dpm.setActiveAdmin(admin1, false);
2501 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2502
2503 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2504 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002505
2506 public void testSetMaximumTimeToLock() {
2507 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2508
2509 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2510 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2511
Pavel Grafov75c0a892017-05-18 17:28:27 +01002512 reset(getServices().powerManagerInternal);
2513 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002514
2515 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002516 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2517 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002518 reset(getServices().powerManagerInternal);
2519 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002520
2521 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002522 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2523 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002524 reset(getServices().powerManagerInternal);
2525 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002526
2527 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002528 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2529 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002530 reset(getServices().powerManagerInternal);
2531 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002532
2533 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002534 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2535 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002536 reset(getServices().powerManagerInternal);
2537 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002538
2539 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002540 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2541 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002542 reset(getServices().powerManagerInternal);
2543 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002544
2545 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002546 reset(getServices().powerManagerInternal);
2547 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002548
Pavel Grafov28939982017-10-03 15:11:52 +01002549 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2550 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2551 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002552 reset(getServices().powerManagerInternal);
2553 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002554
2555 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002556 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2557 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002558 reset(getServices().powerManagerInternal);
2559 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002560
Pavel Grafov28939982017-10-03 15:11:52 +01002561 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002562 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002563 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2564 verifyStayOnWhilePluggedCleared(false);
2565 }
2566
2567 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2568 // uses separate challenge.
2569 public void testSetMaximumTimeToLockProfile() throws Exception {
2570 final int PROFILE_USER = 15;
2571 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2572 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2573 mContext.binder.callingUid = PROFILE_ADMIN;
2574 final DevicePolicyManagerInternal dpmi =
2575 LocalServices.getService(DevicePolicyManagerInternal.class);
2576
2577 dpm.setMaximumTimeToLock(admin1, 0);
2578
2579 reset(getServices().powerManagerInternal);
2580 reset(getServices().settings);
2581
2582 // First add timeout for the profile.
2583 dpm.setMaximumTimeToLock(admin1, 10);
2584 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2585
2586 reset(getServices().powerManagerInternal);
2587 reset(getServices().settings);
2588
2589 // Add separate challenge
2590 when(getServices().lockPatternUtils
2591 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2592 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2593
2594 verifyScreenTimeoutCall(10L, PROFILE_USER);
2595 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2596
2597 reset(getServices().powerManagerInternal);
2598 reset(getServices().settings);
2599
2600 // Remove the timeout.
2601 dpm.setMaximumTimeToLock(admin1, 0);
2602 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2603 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2604
2605 reset(getServices().powerManagerInternal);
2606 reset(getServices().settings);
2607
2608 // Add it back.
2609 dpm.setMaximumTimeToLock(admin1, 10);
2610 verifyScreenTimeoutCall(10L, PROFILE_USER);
2611 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2612
2613 reset(getServices().powerManagerInternal);
2614 reset(getServices().settings);
2615
2616 // Remove separate challenge.
2617 reset(getServices().lockPatternUtils);
2618 when(getServices().lockPatternUtils
2619 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2620 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002621 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002622
2623 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2624 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2625
2626 reset(getServices().powerManagerInternal);
2627 reset(getServices().settings);
2628
2629 // Remove the timeout.
2630 dpm.setMaximumTimeToLock(admin1, 0);
2631 verifyScreenTimeoutCall(null, PROFILE_USER);
2632 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002633 }
2634
Michal Karpinski943aabd2016-10-06 11:09:25 +01002635 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2636 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2637 setupDeviceOwner();
2638 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2639
Michal Karpinskid084ca52017-01-18 15:54:18 +00002640 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2641 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2642 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2643 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2644 - ONE_MINUTE;
2645
2646 // verify that the minimum timeout cannot be modified on user builds (system property is
2647 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002648 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002649
2650 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2651 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2652 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2653
Pavel Grafov75c0a892017-05-18 17:28:27 +01002654 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002655
2656 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002657 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002658
Michal Karpinskid084ca52017-01-18 15:54:18 +00002659 // reset to default (0 means the admin is not participating, so default should be returned)
2660 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002661
2662 // aggregation should be the default if unset by any admin
2663 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2664 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2665
2666 // admin not participating by default
2667 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2668
2669 //clamping from the top
2670 dpm.setRequiredStrongAuthTimeout(admin1,
2671 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2672 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2673 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2674 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2675 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2676
Michal Karpinskid084ca52017-01-18 15:54:18 +00002677 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002678 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2679 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2680 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2681 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2682
2683 // clamping from the bottom
2684 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2685 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2686 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2687
Michal Karpinskid084ca52017-01-18 15:54:18 +00002688 // values within range
2689 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2691 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2692
2693 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002696
2697 // reset to default
2698 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2699 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2700 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2701 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2702
2703 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002704 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2705 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002706 }
2707
Pavel Grafov28939982017-10-03 15:11:52 +01002708 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002709 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002710 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002711 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002712 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002713 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002714 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002715 }
Pavel Grafov28939982017-10-03 15:11:52 +01002716 }
2717
2718 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002719 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2720 // UnfinishedVerificationException.
2721 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002722
Esteban Talavera01576862016-12-15 11:16:44 +00002723 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002724 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002725 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002726 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002727 .thenReturn(false);
2728 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2730 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002731 .thenReturn(true);
2732 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2733
2734 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002735 }
Victor Chang3e794af2016-03-04 13:48:17 +00002736
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002737 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2738 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002739 mContext.packageName = admin1.getPackageName();
2740 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002741 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2743 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2744 false);
2745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2746 }
2747
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002748 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2749 setup_DeviceAdminFeatureOff();
2750 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2751 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2752 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2753 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2754 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2755 assertCheckProvisioningPreCondition(
2756 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2757 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2758 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2759 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2760 }
2761
Esteban Talavera01576862016-12-15 11:16:44 +00002762 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002763 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002764 .thenReturn(false);
2765 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002766 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2767 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002768 .thenReturn(true);
2769 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2770
2771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002772 }
Victor Chang3e794af2016-03-04 13:48:17 +00002773
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002774 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2775 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002776 mContext.packageName = admin1.getPackageName();
2777 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002778 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2779 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2780 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2781 false);
2782 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2783
2784 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002785 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002786 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2787 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2789 true);
2790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2791 }
2792
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002793 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2794 setup_ManagedProfileFeatureOff();
2795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2796 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2797 DevicePolicyManager.CODE_OK);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2799 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2800 assertCheckProvisioningPreCondition(
2801 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2802 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2803 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2804 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2805
2806 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002807 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002808 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2809 DevicePolicyManager.CODE_OK);
2810 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2811 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2812 assertCheckProvisioningPreCondition(
2813 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2814 DevicePolicyManager.CODE_OK);
2815 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2816 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2817 }
2818
Esteban Talavera01576862016-12-15 11:16:44 +00002819 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002820 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002821 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002822 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2823 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002824 .thenReturn(true);
2825 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2826
2827 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002828 }
Victor Chang3e794af2016-03-04 13:48:17 +00002829
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002830 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2831 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002832 mContext.packageName = admin1.getPackageName();
2833 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002834 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2836 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2837 false /* because of non-split user */);
2838 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2839 false /* because of non-split user */);
2840 }
2841
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002842 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002843 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002844 setup_nonSplitUser_firstBoot_primaryUser();
2845 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2846 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2847 DevicePolicyManager.CODE_OK);
2848 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2849 DevicePolicyManager.CODE_OK);
2850 assertCheckProvisioningPreCondition(
2851 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2852 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2853 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2854 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2855 }
2856
Esteban Talavera01576862016-12-15 11:16:44 +00002857 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002858 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002859 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002860 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2861 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002862 .thenReturn(true);
2863 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2864
2865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002866 }
Victor Chang3e794af2016-03-04 13:48:17 +00002867
Nicolas Prevot45d29072017-01-18 16:11:19 +00002868 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2869 setDeviceOwner();
2870 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2871 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2872 }
2873
2874 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2875 setup_nonSplitUser_withDo_primaryUser();
2876 final int MANAGED_PROFILE_USER_ID = 18;
2877 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2878 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002879 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002880 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002881 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002882 true)).thenReturn(true);
2883 }
2884
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002885 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2886 throws Exception {
2887 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002888 mContext.packageName = admin1.getPackageName();
2889 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002890 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2891 false/* because of completed device setup */);
2892 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2893 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2894 false/* because of non-split user */);
2895 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2896 false/* because of non-split user */);
2897 }
2898
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002899 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2900 throws Exception {
2901 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2902 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2903 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2904 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2905 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2906 DevicePolicyManager.CODE_OK);
2907 assertCheckProvisioningPreCondition(
2908 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2909 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2910 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2911 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2912 }
2913
Nicolas Prevot45d29072017-01-18 16:11:19 +00002914 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2915 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002916 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002917 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2918
2919 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2920 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002922
2923 // COMP mode is allowed.
2924 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2925 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002926 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002927
Nicolas Prevot45d29072017-01-18 16:11:19 +00002928 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002929 assertCheckProvisioningPreCondition(
2930 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002931 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002932 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002933 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2934 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2935 }
Esteban Talavera01576862016-12-15 11:16:44 +00002936
Nicolas Prevot45d29072017-01-18 16:11:19 +00002937 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2938 setup_nonSplitUser_withDo_primaryUser();
2939 mContext.packageName = admin1.getPackageName();
2940 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2941 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2942 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002943 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002944 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2945 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2946 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002947 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002948 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2949 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2950 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2951 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2952 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002953 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002954 assertCheckProvisioningPreCondition(
2955 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002956 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002957 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2959 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2960 }
Esteban Talavera01576862016-12-15 11:16:44 +00002961
Nicolas Prevot45d29072017-01-18 16:11:19 +00002962 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2963 throws Exception {
2964 setup_nonSplitUser_withDo_primaryUser();
2965 mContext.packageName = admin1.getPackageName();
2966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002967 // The DO should not be allowed to initiate provisioning if the restriction is set by
2968 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002969 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +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_SYSTEM);
2977 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2978 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002979 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2980
2981 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002982 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002983 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002984 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002985 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2986 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2987 }
2988
2989 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2990 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2991 mContext.packageName = admin1.getPackageName();
2992 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2993
2994 // We can delete the managed profile to create a new one, so provisioning is allowed.
2995 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2996 DevicePolicyManager.CODE_OK);
2997 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2998 assertCheckProvisioningPreCondition(
2999 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3000 DpmMockContext.ANOTHER_PACKAGE_NAME,
3001 DevicePolicyManager.CODE_OK);
3002 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3003 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3004 }
3005
3006 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3007 throws Exception {
3008 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3009 mContext.packageName = admin1.getPackageName();
3010 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003011 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003012 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3013 eq(UserHandle.SYSTEM)))
3014 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003015 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003016 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3017 eq(UserHandle.SYSTEM)))
3018 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003019
3020 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003021 assertCheckProvisioningPreCondition(
3022 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3023 DpmMockContext.ANOTHER_PACKAGE_NAME,
3024 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3025 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3026 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003027
3028 // But the device owner can still do it because it has set the restriction itself.
3029 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3030 DevicePolicyManager.CODE_OK);
3031 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003032 }
3033
3034 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003035 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003036 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003037 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3038 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003039 .thenReturn(false);
3040 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3041
3042 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003043 }
Victor Chang3e794af2016-03-04 13:48:17 +00003044
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003045 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3046 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003047 mContext.packageName = admin1.getPackageName();
3048 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3050 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3051 false /* because canAddMoreManagedProfiles returns false */);
3052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3053 true);
3054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3055 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003056 }
3057
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003058 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3059 throws Exception {
3060 setup_splitUser_firstBoot_systemUser();
3061 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3062 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3063 DevicePolicyManager.CODE_OK);
3064 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003065 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003066 assertCheckProvisioningPreCondition(
3067 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3068 DevicePolicyManager.CODE_OK);
3069 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3070 DevicePolicyManager.CODE_SYSTEM_USER);
3071 }
3072
Esteban Talavera01576862016-12-15 11:16:44 +00003073 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003074 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003075 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003076 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3077 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003078 .thenReturn(false);
3079 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3080
3081 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003082 }
Victor Chang3e794af2016-03-04 13:48:17 +00003083
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3085 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003086 mContext.packageName = admin1.getPackageName();
3087 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003088 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3089 true/* it's undefined behavior. Can be changed into false in the future */);
3090 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3091 false /* because canAddMoreManagedProfiles returns false */);
3092 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3093 true/* it's undefined behavior. Can be changed into false in the future */);
3094 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3095 false/* because calling uid is system user */);
3096 }
3097
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003098 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3099 throws Exception {
3100 setup_splitUser_afterDeviceSetup_systemUser();
3101 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3102 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3103 DevicePolicyManager.CODE_OK);
3104 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003105 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003106 assertCheckProvisioningPreCondition(
3107 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3108 DevicePolicyManager.CODE_OK);
3109 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3110 DevicePolicyManager.CODE_SYSTEM_USER);
3111 }
3112
Esteban Talavera01576862016-12-15 11:16:44 +00003113 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003114 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003115 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003116 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3117 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003118 true)).thenReturn(true);
3119 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3120
3121 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003122 }
Victor Chang3e794af2016-03-04 13:48:17 +00003123
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003124 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3125 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003126 mContext.packageName = admin1.getPackageName();
3127 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003128 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3129 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3130 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3131 true);
3132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003133 }
3134
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003135 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003136 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003137 setup_splitUser_firstBoot_primaryUser();
3138 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3139 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3140 DevicePolicyManager.CODE_OK);
3141 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3142 DevicePolicyManager.CODE_OK);
3143 assertCheckProvisioningPreCondition(
3144 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3145 DevicePolicyManager.CODE_OK);
3146 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3147 DevicePolicyManager.CODE_OK);
3148 }
3149
Esteban Talavera01576862016-12-15 11:16:44 +00003150 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003151 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003152 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003153 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3154 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003155 true)).thenReturn(true);
3156 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3157
3158 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003159 }
Victor Chang3e794af2016-03-04 13:48:17 +00003160
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3162 throws Exception {
3163 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003164 mContext.packageName = admin1.getPackageName();
3165 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003166 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3167 true/* it's undefined behavior. Can be changed into false in the future */);
3168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3170 true/* it's undefined behavior. Can be changed into false in the future */);
3171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3172 false/* because user setup completed */);
3173 }
3174
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003175 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003176 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003177 setup_splitUser_afterDeviceSetup_primaryUser();
3178 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3179 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3180 DevicePolicyManager.CODE_OK);
3181 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3182 DevicePolicyManager.CODE_OK);
3183 assertCheckProvisioningPreCondition(
3184 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3185 DevicePolicyManager.CODE_OK);
3186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3187 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3188 }
3189
Esteban Talavera01576862016-12-15 11:16:44 +00003190 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003191 setDeviceOwner();
3192
Pavel Grafov75c0a892017-05-18 17:28:27 +01003193 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003194 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003195 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3196 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003197 .thenReturn(false);
3198 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3199
3200 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003201 }
Victor Chang3e794af2016-03-04 13:48:17 +00003202
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003203 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3204 throws Exception {
3205 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003206 mContext.packageName = admin1.getPackageName();
3207 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003208 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3209 false /* can't provision managed profile on system user */);
3210 }
3211
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003212 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003213 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003214 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3215 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3216 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3217 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3218 }
3219
3220 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003221 setDeviceOwner();
3222
Pavel Grafov75c0a892017-05-18 17:28:27 +01003223 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003224 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003225 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3226 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003227 true)).thenReturn(true);
3228 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3229
3230 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003231 }
Victor Chang3e794af2016-03-04 13:48:17 +00003232
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003233 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3234 throws Exception {
3235 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003236 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3237 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003238 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3239 }
3240
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003241 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003242 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003243 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3244 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003245
3246 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003247 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3248 DevicePolicyManager.CODE_OK);
3249 }
3250
3251 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003252 setDeviceOwner();
3253
Pavel Grafov75c0a892017-05-18 17:28:27 +01003254 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003255 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003256 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3257 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003258 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3259 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003260 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003261 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003262 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003263 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003264 true)).thenReturn(true);
3265 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3266
3267 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003268 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003269
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003270 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3271 throws Exception {
3272 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003273 mContext.packageName = admin1.getPackageName();
3274 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003275 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3276 }
3277
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003278 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3279 throws Exception {
3280 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3281 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3283 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3284 }
3285
3286 public void testCheckProvisioningPreCondition_permission() {
3287 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003288 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3289 () -> dpm.checkProvisioningPreCondition(
3290 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003291 }
3292
Victor Chang3577ed22016-08-25 18:49:26 +01003293 public void testForceUpdateUserSetupComplete_permission() {
3294 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003295 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3296 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003297 }
3298
3299 public void testForceUpdateUserSetupComplete_systemUser() {
3300 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3301 // GIVEN calling from user 20
3302 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003303 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3304 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003305 }
3306
3307 public void testForceUpdateUserSetupComplete_userbuild() {
3308 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3309 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3310
3311 final int userId = UserHandle.USER_SYSTEM;
3312 // GIVEN userComplete is false in SettingsProvider
3313 setUserSetupCompleteForUser(false, userId);
3314
3315 // GIVEN userComplete is true in DPM
3316 DevicePolicyManagerService.DevicePolicyData userData =
3317 new DevicePolicyManagerService.DevicePolicyData(userId);
3318 userData.mUserSetupComplete = true;
3319 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3320
3321 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003322 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003323
3324 assertTrue(dpms.hasUserSetupCompleted());
3325
3326 dpm.forceUpdateUserSetupComplete();
3327
3328 // THEN the state in dpms is not changed
3329 assertTrue(dpms.hasUserSetupCompleted());
3330 }
3331
3332 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3333 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3334 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3335
3336 final int userId = UserHandle.USER_SYSTEM;
3337 // GIVEN userComplete is false in SettingsProvider
3338 setUserSetupCompleteForUser(false, userId);
3339
3340 // GIVEN userComplete is true in DPM
3341 DevicePolicyManagerService.DevicePolicyData userData =
3342 new DevicePolicyManagerService.DevicePolicyData(userId);
3343 userData.mUserSetupComplete = true;
3344 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3345
3346 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003347 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003348
3349 assertTrue(dpms.hasUserSetupCompleted());
3350
3351 dpm.forceUpdateUserSetupComplete();
3352
3353 // THEN the state in dpms is not changed
3354 assertFalse(dpms.hasUserSetupCompleted());
3355 }
3356
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003357 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003358 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003359 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003360
3361 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3362 runAsCaller(mAdmin1Context, dpms, dpm -> {
3363 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3364 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003365 }
3366
3367 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3368 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3369 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003370
3371 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3372 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003373 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003374 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3375 .thenReturn(true);
3376
3377 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003378 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003379
3380 // Enabling logging should not change the timestamp.
3381 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003382 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003383 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003384 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003385 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003386 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003387
3388 // Retrieving the logs should update the timestamp.
3389 final long beforeRetrieval = System.currentTimeMillis();
3390 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003391 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003392 final long afterRetrieval = System.currentTimeMillis();
3393 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3394 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3395
3396 // Retrieving the pre-boot logs should update the timestamp.
3397 Thread.sleep(2);
3398 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003399 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003400 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3401
3402 // Checking the timestamp again should not change it.
3403 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003404 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003405
3406 // Retrieving the logs again should update the timestamp.
3407 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003408 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003409 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3410
3411 // Disabling logging should not change the timestamp.
3412 Thread.sleep(2);
3413 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003414 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003415
3416 // Restarting the DPMS should not lose the timestamp.
3417 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003418 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003419
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003420 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3421 mContext.binder.callingUid = 1234567;
3422 mContext.callerPermissions.add(permission.MANAGE_USERS);
3423 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3424 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3425
3426 // System can retrieve the timestamp.
3427 mContext.binder.clearCallingIdentity();
3428 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3429
3430 // Removing the device owner should clear the timestamp.
3431 clearDeviceOwner();
3432 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003433 }
3434
yuemingw0de748d2017-11-15 19:22:27 +00003435 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3436 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3437 setupDeviceOwner();
3438 assertExpectException(SecurityException.class, null, () ->
3439 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3440 }
3441
yuemingwc0281f12018-03-28 15:58:49 +01003442 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003443 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3444 setupDeviceOwner();
3445 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003446 verify(getServices().settings).settingsSystemPutStringForUser(
3447 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3448 }
3449
3450 public void testSetSystemSettingWithPO() throws Exception {
3451 setupProfileOwner();
3452 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3453 verify(getServices().settings).settingsSystemPutStringForUser(
3454 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003455 }
3456
yuemingwe43cdf72017-10-12 16:52:11 +01003457 public void testSetTime() throws Exception {
3458 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3459 setupDeviceOwner();
3460 dpm.setTime(admin1, 0);
3461 verify(getServices().alarmManager).setTime(0);
3462 }
3463
3464 public void testSetTimeFailWithPO() throws Exception {
3465 setupProfileOwner();
3466 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3467 }
3468
3469 public void testSetTimeWithAutoTimeOn() throws Exception {
3470 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3471 setupDeviceOwner();
3472 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3473 .thenReturn(1);
3474 assertFalse(dpm.setTime(admin1, 0));
3475 }
3476
3477 public void testSetTimeZone() throws Exception {
3478 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3479 setupDeviceOwner();
3480 dpm.setTimeZone(admin1, "Asia/Shanghai");
3481 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3482 }
3483
3484 public void testSetTimeZoneFailWithPO() throws Exception {
3485 setupProfileOwner();
3486 assertExpectException(SecurityException.class, null,
3487 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3488 }
3489
3490 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3491 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3492 setupDeviceOwner();
3493 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3494 .thenReturn(1);
3495 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3496 }
3497
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003498 public void testGetLastBugReportRequestTime() throws Exception {
3499 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3500 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003501
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003502 mContext.packageName = admin1.getPackageName();
3503 mContext.applicationInfo = new ApplicationInfo();
3504 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3505 .thenReturn(Color.WHITE);
3506 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3507 anyObject())).thenReturn(Color.WHITE);
3508
Esteban Talaverad36dd152016-12-15 08:51:45 +00003509 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3510 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003511 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003512
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003513 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003514 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003515
3516 // Requesting a bug report should update the timestamp.
3517 final long beforeRequest = System.currentTimeMillis();
3518 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003519 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003520 final long afterRequest = System.currentTimeMillis();
3521 assertTrue(bugReportRequestTime >= beforeRequest);
3522 assertTrue(bugReportRequestTime <= afterRequest);
3523
3524 // Checking the timestamp again should not change it.
3525 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003526 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003527
3528 // Restarting the DPMS should not lose the timestamp.
3529 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003530 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003531
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003532 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3533 mContext.binder.callingUid = 1234567;
3534 mContext.callerPermissions.add(permission.MANAGE_USERS);
3535 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3536 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3537
3538 // System can retrieve the timestamp.
3539 mContext.binder.clearCallingIdentity();
3540 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3541
3542 // Removing the device owner should clear the timestamp.
3543 clearDeviceOwner();
3544 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003545 }
3546
3547 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3548 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3549 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003550 mContext.packageName = admin1.getPackageName();
3551 mContext.applicationInfo = new ApplicationInfo();
3552 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3553 .thenReturn(Color.WHITE);
3554 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3555 anyObject())).thenReturn(Color.WHITE);
3556
3557 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3558 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003559 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003560 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003561 .thenReturn(true);
3562
3563 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003564 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003565
3566 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3567 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003568 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003569
3570 // Enabling logging should not change the timestamp.
3571 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003572 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003573
3574 // Retrieving the logs should update the timestamp.
3575 final long beforeRetrieval = System.currentTimeMillis();
3576 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003577 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003578 final long afterRetrieval = System.currentTimeMillis();
3579 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3580 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3581
3582 // Checking the timestamp again should not change it.
3583 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003584 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003585
3586 // Retrieving the logs again should update the timestamp.
3587 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003588 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003589 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3590
3591 // Disabling logging should not change the timestamp.
3592 Thread.sleep(2);
3593 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003594 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003595
3596 // Restarting the DPMS should not lose the timestamp.
3597 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003598 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3599
3600 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3601 mContext.binder.callingUid = 1234567;
3602 mContext.callerPermissions.add(permission.MANAGE_USERS);
3603 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3604 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3605
3606 // System can retrieve the timestamp.
3607 mContext.binder.clearCallingIdentity();
3608 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3609
3610 // Removing the device owner should clear the timestamp.
3611 clearDeviceOwner();
3612 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003613 }
3614
Tony Mak2f26b792016-11-28 17:54:51 +00003615 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3616 // Setup device owner.
3617 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3618 setupDeviceOwner();
3619
3620 // Only device owner is setup, the result list should be empty.
3621 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3622 MoreAsserts.assertEmpty(targetUsers);
3623
3624 // Setup a managed profile managed by the same admin.
3625 final int MANAGED_PROFILE_USER_ID = 15;
3626 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3627 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3628
3629 // Add a secondary user, it should never talk with.
3630 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003631 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003632
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003633 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3634 // other.
3635 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3636 MoreAsserts.assertEmpty(targetUsers);
3637
3638 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3639 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3640 MoreAsserts.assertEmpty(targetUsers);
3641
3642 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003643 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003644 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3645 dpm.setAffiliationIds(admin1, userAffiliationIds);
3646
3647 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3648 dpm.setAffiliationIds(admin1, userAffiliationIds);
3649
Tony Mak2f26b792016-11-28 17:54:51 +00003650 // Calling from device owner admin, the result list should just contain the managed
3651 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003652 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003653 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3654 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3655
3656 // Calling from managed profile admin, the result list should just contain the system
3657 // user id.
3658 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3659 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3660 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003661
3662 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003663 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003664
3665 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3666 // to each other.
3667 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3668 MoreAsserts.assertEmpty(targetUsers);
3669
3670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3671 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3672 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003673 }
3674
3675 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3676 // Setup a device owner.
3677 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3678 setupDeviceOwner();
3679
3680 // Set up a managed profile managed by different package.
3681 final int MANAGED_PROFILE_USER_ID = 15;
3682 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3683 final ComponentName adminDifferentPackage =
3684 new ComponentName("another.package", "whatever.class");
3685 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3686
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003687 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003688 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003689 dpm.setAffiliationIds(admin1, userAffiliationIds);
3690
3691 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3692 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3693
Tony Mak2f26b792016-11-28 17:54:51 +00003694 // Calling from device owner admin, we should get zero bind device admin target users as
3695 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003696 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003697 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3698 MoreAsserts.assertEmpty(targetUsers);
3699
3700 // Calling from managed profile admin, we should still get zero target users for the same
3701 // reason.
3702 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3703 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3704 MoreAsserts.assertEmpty(targetUsers);
3705 }
3706
Jason Parks3c13b642017-11-28 15:39:43 -06003707 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003708 verifyLockTaskState(userId, new String[0],
3709 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003710 }
3711
3712 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3713 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003714 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003715 }
3716
3717 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3718 int flags) throws Exception {
3719 mContext.binder.callingUid = uid;
3720 dpm.setLockTaskPackages(who, packages);
3721 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3722 for (String p : packages) {
3723 assertTrue(dpm.isLockTaskPermitted(p));
3724 }
3725 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3726 // Test to see if set lock task features can be set
3727 dpm.setLockTaskFeatures(who, flags);
3728 verifyLockTaskState(userId, packages, flags);
3729 }
3730
3731 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3732 int flags) throws Exception {
3733 mContext.binder.callingUid = uid;
3734 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3735 () -> dpm.setLockTaskPackages(who, packages));
3736 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3737 () -> dpm.getLockTaskPackages(who));
3738 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3739 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3740 () -> dpm.setLockTaskFeatures(who, flags));
3741 }
3742
Charles Hee078db72017-10-19 18:03:20 +01003743 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003744 // Setup a device owner.
3745 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3746 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003747 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003748 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003749
3750 // Set up a managed profile managed by different package (package name shouldn't matter)
3751 final int MANAGED_PROFILE_USER_ID = 15;
3752 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3753 final ComponentName adminDifferentPackage =
3754 new ComponentName("another.package", "whatever.class");
3755 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003756 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3757
3758 // Setup a PO on the secondary user
3759 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3760 setAsProfileOwner(admin3);
3761 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003762
3763 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003764 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003765 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003766 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3767 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003768 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3769
3770 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3771 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003772 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3773 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003774 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003775
3776 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3777 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3778 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003779 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003780 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3781 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003782 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003783
3784 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003785 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3787 dpm.setAffiliationIds(admin1, userAffiliationIds);
3788
3789 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3790 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3791
3792 // Now the managed profile can set lock task packages.
3793 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3794 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3795 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3796 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003797 // And it can set lock task features.
3798 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003799 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003800
3801 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003802 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003803 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3804 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003805 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3806 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003807 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003808 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003809
Jason Parks3c13b642017-11-28 15:39:43 -06003810 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003811 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3812 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003813
3814 }
3815
3816 public void testLockTaskPolicyForProfileOwner() throws Exception {
3817 // Setup a PO
3818 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3819 setAsProfileOwner(admin1);
3820 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3821
3822 final String[] poPackages = {"poPackage1", "poPackage2"};
3823 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003824 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3825 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003826 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3827 poPackages, poFlags);
3828
3829 // Set up a managed profile managed by different package (package name shouldn't matter)
3830 final int MANAGED_PROFILE_USER_ID = 15;
3831 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3832 final ComponentName adminDifferentPackage =
3833 new ComponentName("another.package", "whatever.class");
3834 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3835 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3836
3837 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3838 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3839 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3840 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003841 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3842 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003843 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003844 }
3845
Benjamin Franzcaffa772018-02-05 16:36:10 +00003846 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3847 // Setup a device owner.
3848 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3849 setupDeviceOwner();
3850 // Lock task policy is updated when loading user data.
3851 verifyLockTaskState(UserHandle.USER_SYSTEM);
3852
3853 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3854 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3855 assertExpectException(IllegalArgumentException.class,
3856 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3857 () -> dpm.setLockTaskFeatures(admin1, flags));
3858 }
3859
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003860 public void testIsDeviceManaged() throws Exception {
3861 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3862 setupDeviceOwner();
3863
3864 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3865 // find out that the device has a device owner.
3866 assertTrue(dpm.isDeviceManaged());
3867 mContext.binder.callingUid = 1234567;
3868 mContext.callerPermissions.add(permission.MANAGE_USERS);
3869 assertTrue(dpm.isDeviceManaged());
3870 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3871 mContext.binder.clearCallingIdentity();
3872 assertTrue(dpm.isDeviceManaged());
3873
3874 clearDeviceOwner();
3875
3876 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3877 // not have a device owner.
3878 mContext.binder.callingUid = 1234567;
3879 mContext.callerPermissions.add(permission.MANAGE_USERS);
3880 assertFalse(dpm.isDeviceManaged());
3881 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3882 mContext.binder.clearCallingIdentity();
3883 assertFalse(dpm.isDeviceManaged());
3884 }
3885
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003886 public void testDeviceOwnerOrganizationName() throws Exception {
3887 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3888 setupDeviceOwner();
3889
3890 dpm.setOrganizationName(admin1, "organization");
3891
3892 // Device owner can retrieve organization managing the device.
3893 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3894
3895 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3896 mContext.binder.callingUid = 1234567;
3897 mContext.callerPermissions.add(permission.MANAGE_USERS);
3898 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3899 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3900
3901 // System can retrieve organization managing the device.
3902 mContext.binder.clearCallingIdentity();
3903 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3904
3905 // Removing the device owner clears the organization managing the device.
3906 clearDeviceOwner();
3907 assertNull(dpm.getDeviceOwnerOrganizationName());
3908 }
3909
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003910 public void testWipeDataManagedProfile() throws Exception {
3911 final int MANAGED_PROFILE_USER_ID = 15;
3912 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3913 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3914 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3915
3916 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003917 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003918 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003919 // Get mock reason string since we throw an IAE with empty string input.
3920 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3921 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003922
3923 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003924 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003925 MANAGED_PROFILE_USER_ID);
3926 }
3927
3928 public void testWipeDataManagedProfileDisallowed() throws Exception {
3929 final int MANAGED_PROFILE_USER_ID = 15;
3930 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3931 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3932
3933 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003934 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003935 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3936
Pavel Grafov75c0a892017-05-18 17:28:27 +01003937 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003938 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3939 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3940 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003941 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3942 thenReturn("Just a test string.");
3943
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003944 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003945 // The PO is not allowed to remove the profile if the user restriction was set on the
3946 // profile by the system
3947 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3948 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003949 }
3950
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003951 public void testWipeDataDeviceOwner() throws Exception {
3952 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003953 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003954 UserManager.DISALLOW_FACTORY_RESET,
3955 UserHandle.SYSTEM))
3956 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003957 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3958 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003959
3960 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003961 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003962 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3963 /*wipeEuicc=*/ eq(false));
3964 }
3965
3966 public void testWipeEuiccDataEnabled() throws Exception {
3967 setDeviceOwner();
3968 when(getServices().userManager.getUserRestrictionSource(
3969 UserManager.DISALLOW_FACTORY_RESET,
3970 UserHandle.SYSTEM))
3971 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003972 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3973 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003974
3975 dpm.wipeData(WIPE_EUICC);
3976 verify(getServices().recoverySystem).rebootWipeUserData(
3977 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3978 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003979 }
3980
3981 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3982 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003983 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003984 UserManager.DISALLOW_FACTORY_RESET,
3985 UserHandle.SYSTEM))
3986 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003987 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3988 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003989 // The DO is not allowed to wipe the device if the user restriction was set
3990 // by the system
3991 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3992 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003993 }
3994
3995 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3996 final int MANAGED_PROFILE_USER_ID = 15;
3997 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3998 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3999
4000 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004001 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004002 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4003
Pavel Grafov75c0a892017-05-18 17:28:27 +01004004 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004005 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4006 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4007 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4008
4009 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4010 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4011
4012 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4013 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4014 // Failed password attempts on the parent user are taken into account, as there isn't a
4015 // separate work challenge.
4016 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4017 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4018 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4019
4020 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4021 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004022 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004023 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004024 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004025 }
4026
4027 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4028 throws Exception {
4029 final int MANAGED_PROFILE_USER_ID = 15;
4030 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4031 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4032
4033 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004034 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004035 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4036
Pavel Grafov75c0a892017-05-18 17:28:27 +01004037 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004038 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4039 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4040 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4041
4042 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4043 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4044
4045 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4046 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4047 // Failed password attempts on the parent user are taken into account, as there isn't a
4048 // separate work challenge.
4049 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4050 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4051 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4052
4053 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4054 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004055 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004056 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004057 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004058 }
4059
4060 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4061 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004062 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004063 UserManager.DISALLOW_FACTORY_RESET,
4064 UserHandle.SYSTEM))
4065 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4066
4067 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4068
4069 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4070 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4071 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4072 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4073 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4074
4075 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4076 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004077 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004078 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4079 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004080 }
4081
4082 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4083 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004084 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004085 UserManager.DISALLOW_FACTORY_RESET,
4086 UserHandle.SYSTEM))
4087 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4088
4089 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4090
4091 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4092 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4093 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4094 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4095 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4096
4097 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004098 verifyZeroInteractions(getServices().recoverySystem);
4099 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004100 .removeUserEvenWhenDisallowed(anyInt());
4101 }
4102
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004103 public void testGetPermissionGrantState() throws Exception {
4104 final String permission = "some.permission";
4105 final String app1 = "com.example.app1";
4106 final String app2 = "com.example.app2";
4107
Pavel Grafov75c0a892017-05-18 17:28:27 +01004108 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004109 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004111 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004112 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004113 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4114 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004115 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004116 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004117 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004118 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004119 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004120 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4121
4122 // System can retrieve permission grant state.
4123 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004124 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004125 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4126 dpm.getPermissionGrantState(null, app1, permission));
4127 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4128 dpm.getPermissionGrantState(null, app2, permission));
4129
4130 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004131 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4132 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004133 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4134 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004135
4136 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004137 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4138 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004139 setAsProfileOwner(admin1);
4140 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4141 dpm.getPermissionGrantState(admin1, app1, permission));
4142 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4143 dpm.getPermissionGrantState(admin1, app2, permission));
4144 }
4145
Rubin Xuaab7a412016-12-30 21:13:29 +00004146 public void testResetPasswordWithToken() throws Exception {
4147 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4148 setupDeviceOwner();
4149 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004150 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4151 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4152
Rubin Xuaab7a412016-12-30 21:13:29 +00004153 // test adding a token
4154 final byte[] token = new byte[32];
4155 final long handle = 123456;
4156 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004157 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4158 nullable(EscrowTokenStateChangeCallback.class)))
4159 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004160 assertTrue(dpm.setResetPasswordToken(admin1, token));
4161
4162 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004164 .thenReturn(true);
4165 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4166
4167 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004168 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004169 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004170 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004171 eq(UserHandle.USER_SYSTEM)))
4172 .thenReturn(true);
4173 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4174
4175 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004176 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004177 .thenReturn(true);
4178 assertTrue(dpm.clearResetPasswordToken(admin1));
4179 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004180
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004181 public void testIsActivePasswordSufficient() throws Exception {
4182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4183 mContext.packageName = admin1.getPackageName();
4184 setupDeviceOwner();
4185
4186 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4187 dpm.setPasswordMinimumLength(admin1, 8);
4188 dpm.setPasswordMinimumLetters(admin1, 6);
4189 dpm.setPasswordMinimumLowerCase(admin1, 3);
4190 dpm.setPasswordMinimumUpperCase(admin1, 1);
4191 dpm.setPasswordMinimumNonLetter(admin1, 1);
4192 dpm.setPasswordMinimumNumeric(admin1, 1);
4193 dpm.setPasswordMinimumSymbols(admin1, 0);
4194
Rubin Xucc391c22018-01-02 20:37:35 +00004195 reset(mContext.spiedContext);
4196
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004197 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4198 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4199 8, 2,
4200 6, 1,
4201 0, 1);
4202
4203 setActivePasswordState(passwordMetricsNoSymbols);
4204 assertTrue(dpm.isActivePasswordSufficient());
4205
4206 initializeDpms();
4207 reset(mContext.spiedContext);
4208 assertTrue(dpm.isActivePasswordSufficient());
4209
4210 // This call simulates the user entering the password for the first time after a reboot.
4211 // This causes password metrics to be reloaded into memory. Until this happens,
4212 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4213 // even if the DPC changes password requirements so that the password no longer meets the
4214 // requirements. This is a known limitation of the current implementation of
4215 // isActivePasswordSufficient() - see b/34218769.
4216 setActivePasswordState(passwordMetricsNoSymbols);
4217 assertTrue(dpm.isActivePasswordSufficient());
4218
4219 dpm.setPasswordMinimumSymbols(admin1, 1);
4220 // This assertion would fail if we had not called setActivePasswordState() again after
4221 // initializeDpms() - see previous comment.
4222 assertFalse(dpm.isActivePasswordSufficient());
4223
4224 initializeDpms();
4225 reset(mContext.spiedContext);
4226 assertFalse(dpm.isActivePasswordSufficient());
4227
4228 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4229 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4230 7, 2,
4231 5, 1,
4232 1, 2);
4233
4234 setActivePasswordState(passwordMetricsWithSymbols);
4235 assertTrue(dpm.isActivePasswordSufficient());
4236 }
4237
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004238 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4239 // If there is no lock screen, the password is considered empty no matter what, because
4240 // it provides no security.
4241 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4242
4243 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4244 mContext.packageName = admin1.getPackageName();
4245 setupDeviceOwner();
4246
4247 // If no password requirements are set, isActivePasswordSufficient should succeed.
4248 assertTrue(dpm.isActivePasswordSufficient());
4249
4250 // Now set some password quality requirements.
4251 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4252
4253 reset(mContext.spiedContext);
4254 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4255 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4256 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4257 8, 2,
4258 6, 1,
4259 0, 1);
4260 // This should be ignored, as there is no lock screen.
4261 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4262 dpm.reportPasswordChanged(userHandle);
4263
4264 // No broadcast should be sent.
4265 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4266 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4267 MockUtils.checkUserHandle(userHandle));
4268
4269 // The active (nonexistent) password doesn't comply with the requirements.
4270 assertFalse(dpm.isActivePasswordSufficient());
4271 }
4272
Pavel Grafov75c0a892017-05-18 17:28:27 +01004273 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4274 throws Exception {
4275 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004276 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004277
Pavel Grafov75c0a892017-05-18 17:28:27 +01004278 dpm.setActivePasswordState(passwordMetrics, userHandle);
4279 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004280
Rubin Xucc391c22018-01-02 20:37:35 +00004281 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4282 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004283 // This broadcast should be sent 4 times:
4284 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4285 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4286 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4287 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4288 // the password change is relevant to and another with the credential owner of said
4289 // userId.
4290 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004291 MockUtils.checkIntentAction(
4292 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4293 MockUtils.checkUserHandle(userHandle));
4294
Pavel Grafov75c0a892017-05-18 17:28:27 +01004295 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4296 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004297 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004298
4299 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4300 MockUtils.checkIntent(intent),
4301 MockUtils.checkUserHandle(userHandle));
4302
4303 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4304 // let it finish with system uid, otherwise it will throw and crash.
4305 flushTasks();
4306
4307 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004308 }
4309
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004310 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4311 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4312 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4313 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4314 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4315 DpmMockContext.SYSTEM_UID);
4316 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4317 DpmMockContext.SYSTEM_UID);
4318
4319 // Set up a device owner.
4320 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004321 setupDeviceOwner();
4322
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004323 // First and second user set IMEs manually.
4324 mContext.binder.callingUid = firstUserSystemUid;
4325 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4326 mContext.binder.callingUid = secondUserSystemUid;
4327 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004328
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004329 // Device owner changes IME for first user.
4330 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004331 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004332 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004333 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004334 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004335 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004336 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004337 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4338 mContext.binder.callingUid = firstUserSystemUid;
4339 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4340 mContext.binder.callingUid = secondUserSystemUid;
4341 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004342
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004343 // Second user changes IME manually.
4344 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4345 mContext.binder.callingUid = firstUserSystemUid;
4346 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4347 mContext.binder.callingUid = secondUserSystemUid;
4348 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004349
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004350 // First user changes IME manually.
4351 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4352 mContext.binder.callingUid = firstUserSystemUid;
4353 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4354 mContext.binder.callingUid = secondUserSystemUid;
4355 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004356
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004357 // Device owner changes IME for first user again.
4358 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004359 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004360 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004361 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004362 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004363 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004364 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4365 mContext.binder.callingUid = firstUserSystemUid;
4366 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4367 mContext.binder.callingUid = secondUserSystemUid;
4368 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004369
4370 // Restarting the DPMS should not lose information.
4371 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004372 mContext.binder.callingUid = firstUserSystemUid;
4373 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4374 mContext.binder.callingUid = secondUserSystemUid;
4375 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004376
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 // Device owner can find out whether it set the current IME itself.
4378 mContext.binder.callingUid = deviceOwnerUid;
4379 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004380
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004382 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004383 mContext.binder.callingUid = firstUserSystemUid;
4384 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4385 mContext.binder.callingUid = secondUserSystemUid;
4386 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004387 }
4388
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004389 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4390 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4391 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4392 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4393 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4394 DpmMockContext.SYSTEM_UID);
4395 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4396 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004397
4398 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004399 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004400 setupProfileOwner();
4401
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004402 // First and second user set IMEs manually.
4403 mContext.binder.callingUid = firstUserSystemUid;
4404 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4405 mContext.binder.callingUid = secondUserSystemUid;
4406 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004407
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004408 // Profile owner changes IME for second user.
4409 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004410 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004411 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004412 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004413 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004414 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004415 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004416 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4417 mContext.binder.callingUid = firstUserSystemUid;
4418 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4419 mContext.binder.callingUid = secondUserSystemUid;
4420 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004421
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004422 // First user changes IME manually.
4423 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4424 mContext.binder.callingUid = firstUserSystemUid;
4425 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4426 mContext.binder.callingUid = secondUserSystemUid;
4427 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004428
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004429 // Second user changes IME manually.
4430 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4431 mContext.binder.callingUid = firstUserSystemUid;
4432 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4433 mContext.binder.callingUid = secondUserSystemUid;
4434 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004435
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004436 // Profile owner changes IME for second user again.
4437 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004438 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004439 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004440 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004441 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004442 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004443 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4444 mContext.binder.callingUid = firstUserSystemUid;
4445 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4446 mContext.binder.callingUid = secondUserSystemUid;
4447 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004448
4449 // Restarting the DPMS should not lose information.
4450 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004451 mContext.binder.callingUid = firstUserSystemUid;
4452 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4453 mContext.binder.callingUid = secondUserSystemUid;
4454 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004455
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004456 // Profile owner can find out whether it set the current IME itself.
4457 mContext.binder.callingUid = profileOwnerUid;
4458 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004460 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004461 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004462 mContext.binder.callingUid = firstUserSystemUid;
4463 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4464 mContext.binder.callingUid = secondUserSystemUid;
4465 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004466 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004467
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004468 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4469 throws Exception {
4470 // Set up a device owner.
4471 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4472 setupDeviceOwner();
4473 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4474 }
4475
4476 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4477 throws Exception {
4478 // Set up a profile owner.
4479 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4480 setupProfileOwner();
4481 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4482 }
4483
4484 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4485 int adminUid) throws Exception {
4486 mContext.binder.callingUid = adminUid;
4487 final int userId = UserHandle.getUserId(adminUid);
4488
4489 final String packageName = "some.package";
4490 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4491 admin1, Collections.singletonList(packageName)));
4492 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4493
4494 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4495 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4496
4497 // Attempt to set to empty list (which means no listener is whitelisted)
4498 mContext.binder.callingUid = adminUid;
4499 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004500 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004501 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4502
4503 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4504 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4505 }
4506
4507 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4508 // Set up a managed profile
4509 final int MANAGED_PROFILE_USER_ID = 15;
4510 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4511 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4512 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4513
4514 final String permittedListener = "some.package";
4515 setupPackageInPackageManager(
4516 permittedListener,
4517 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4518 /*appId=*/ 12345, /*flags=*/ 0);
4519
4520 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4521 admin1, Collections.singletonList(permittedListener)));
4522
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004523 // isNotificationListenerServicePermitted should throw if not called from System.
4524 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4525 () -> dpms.isNotificationListenerServicePermitted(
4526 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004527
4528 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4529 assertTrue(dpms.isNotificationListenerServicePermitted(
4530 permittedListener, MANAGED_PROFILE_USER_ID));
4531 }
4532
4533 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4534 throws Exception {
4535 // Set up a managed profile
4536 final int MANAGED_PROFILE_USER_ID = 15;
4537 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4538 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4539 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4540
4541 final String permittedListener = "permitted.package";
4542 int appId = 12345;
4543 setupPackageInPackageManager(
4544 permittedListener,
4545 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4546 appId, /*flags=*/ 0);
4547
4548 final String notPermittedListener = "not.permitted.package";
4549 setupPackageInPackageManager(
4550 notPermittedListener,
4551 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4552 ++appId, /*flags=*/ 0);
4553
4554 final String systemListener = "system.package";
4555 setupPackageInPackageManager(
4556 systemListener,
4557 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4558 ++appId, ApplicationInfo.FLAG_SYSTEM);
4559
4560 // By default all packages are allowed
4561 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4562
4563 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4564 assertTrue(dpms.isNotificationListenerServicePermitted(
4565 permittedListener, MANAGED_PROFILE_USER_ID));
4566 assertTrue(dpms.isNotificationListenerServicePermitted(
4567 notPermittedListener, MANAGED_PROFILE_USER_ID));
4568 assertTrue(dpms.isNotificationListenerServicePermitted(
4569 systemListener, MANAGED_PROFILE_USER_ID));
4570
4571 // Setting only one package in the whitelist
4572 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4573 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4574 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004575 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004576 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4577 assertEquals(1, permittedListeners.size());
4578 assertEquals(permittedListener, permittedListeners.get(0));
4579
4580 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4581 assertTrue(dpms.isNotificationListenerServicePermitted(
4582 permittedListener, MANAGED_PROFILE_USER_ID));
4583 assertFalse(dpms.isNotificationListenerServicePermitted(
4584 notPermittedListener, MANAGED_PROFILE_USER_ID));
4585 // System packages are always allowed (even if not in the whitelist)
4586 assertTrue(dpms.isNotificationListenerServicePermitted(
4587 systemListener, MANAGED_PROFILE_USER_ID));
4588
4589 // Setting an empty whitelist - only system listeners allowed
4590 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4591 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004592 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004593 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4594
4595 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4596 assertFalse(dpms.isNotificationListenerServicePermitted(
4597 permittedListener, MANAGED_PROFILE_USER_ID));
4598 assertFalse(dpms.isNotificationListenerServicePermitted(
4599 notPermittedListener, MANAGED_PROFILE_USER_ID));
4600 // System packages are always allowed (even if not in the whitelist)
4601 assertTrue(dpms.isNotificationListenerServicePermitted(
4602 systemListener, MANAGED_PROFILE_USER_ID));
4603
4604 // Setting a null whitelist - all listeners allowed
4605 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4606 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4607 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4608
4609 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4610 assertTrue(dpms.isNotificationListenerServicePermitted(
4611 permittedListener, MANAGED_PROFILE_USER_ID));
4612 assertTrue(dpms.isNotificationListenerServicePermitted(
4613 notPermittedListener, MANAGED_PROFILE_USER_ID));
4614 assertTrue(dpms.isNotificationListenerServicePermitted(
4615 systemListener, MANAGED_PROFILE_USER_ID));
4616 }
4617
4618 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4619 throws Exception {
4620 // Set up a managed profile
4621 final int MANAGED_PROFILE_USER_ID = 15;
4622 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4623 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4624 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4625
4626 final String nonSystemPackage = "non.system.package";
4627 int appId = 12345;
4628 setupPackageInPackageManager(
4629 nonSystemPackage,
4630 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4631 appId, /*flags=*/ 0);
4632
4633 final String systemListener = "system.package";
4634 setupPackageInPackageManager(
4635 systemListener,
4636 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4637 ++appId, ApplicationInfo.FLAG_SYSTEM);
4638
4639 // By default all packages are allowed (for all profiles)
4640 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4641
4642 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4643 assertTrue(dpms.isNotificationListenerServicePermitted(
4644 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4645 assertTrue(dpms.isNotificationListenerServicePermitted(
4646 systemListener, MANAGED_PROFILE_USER_ID));
4647 assertTrue(dpms.isNotificationListenerServicePermitted(
4648 nonSystemPackage, UserHandle.USER_SYSTEM));
4649 assertTrue(dpms.isNotificationListenerServicePermitted(
4650 systemListener, UserHandle.USER_SYSTEM));
4651
4652 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4653 // all allowed in primary profile
4654 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4655 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004656 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004657 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4658
4659 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4660 assertFalse(dpms.isNotificationListenerServicePermitted(
4661 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4662 assertTrue(dpms.isNotificationListenerServicePermitted(
4663 systemListener, MANAGED_PROFILE_USER_ID));
4664 assertTrue(dpms.isNotificationListenerServicePermitted(
4665 nonSystemPackage, UserHandle.USER_SYSTEM));
4666 assertTrue(dpms.isNotificationListenerServicePermitted(
4667 systemListener, UserHandle.USER_SYSTEM));
4668 }
4669
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004670 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004671 mServiceContext.packageName = mRealTestContext.getPackageName();
4672 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4673 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004674 setDeviceOwner();
4675
Pavel Grafov75c0a892017-05-18 17:28:27 +01004676 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004677 }
4678
4679 public void testGetOwnerInstalledCaCertsForProfileOwner() 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 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4686 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004687 }
4688
4689 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004690 mServiceContext.packageName = mRealTestContext.getPackageName();
4691 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4692 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004693 setAsProfileOwner(admin1);
4694
Pavel Grafov75c0a892017-05-18 17:28:27 +01004695 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4696 caller.packageName = "com.example.delegate";
4697 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4698 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004699
Pavel Grafov75c0a892017-05-18 17:28:27 +01004700 // Make caller a delegated cert installer.
4701 runAsCaller(mAdmin1Context, dpms,
4702 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004703
4704 verifyCanGetOwnerInstalledCaCerts(null, caller);
4705 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004706 }
4707
Rubin Xucc391c22018-01-02 20:37:35 +00004708 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004709 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4710 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004711 Bundle restriction = new Bundle();
4712 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4713
4714 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4715 RestrictionsListener listener = new RestrictionsListener(mContext);
4716 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4717 new Bundle());
4718 verifyDataSharingChangedBroadcast();
4719 }
4720
4721 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004722 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4723 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004724 Bundle restriction = new Bundle();
4725 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4726
4727 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4728 RestrictionsListener listener = new RestrictionsListener(mContext);
4729 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4730 restriction);
4731 verifyDataSharingChangedBroadcast();
4732 }
4733
4734 public void testDisallowSharingIntoProfileUnchanged() {
4735 RestrictionsListener listener = new RestrictionsListener(mContext);
4736 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4737 new Bundle());
4738 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4739 }
4740
4741 private void verifyDataSharingChangedBroadcast() {
4742 Intent expectedIntent = new Intent(
4743 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4744 expectedIntent.setPackage("com.android.managedprovisioning");
4745 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4746 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4747 MockUtils.checkIntent(expectedIntent),
4748 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4749 }
4750
yuemingwe3d9c092018-01-11 12:11:44 +00004751 public void testOverrideApnAPIsFailWithPO() throws Exception {
4752 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004753 ApnSetting apn = (new ApnSetting.Builder())
4754 .setApnName("test")
4755 .setEntryName("test")
4756 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4757 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004758 assertExpectException(SecurityException.class, null, () ->
4759 dpm.addOverrideApn(admin1, apn));
4760 assertExpectException(SecurityException.class, null, () ->
4761 dpm.updateOverrideApn(admin1, 0, apn));
4762 assertExpectException(SecurityException.class, null, () ->
4763 dpm.removeOverrideApn(admin1, 0));
4764 assertExpectException(SecurityException.class, null, () ->
4765 dpm.getOverrideApns(admin1));
4766 assertExpectException(SecurityException.class, null, () ->
4767 dpm.setOverrideApnsEnabled(admin1, false));
4768 assertExpectException(SecurityException.class, null, () ->
4769 dpm.isOverrideApnEnabled(admin1));
4770 }
4771
Robin Lee2c68dad2017-03-17 12:50:24 +00004772 private void verifyCanGetOwnerInstalledCaCerts(
4773 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004774 final String alias = "cert";
4775 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004776
4777 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004778 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004779 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4780 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004781 }
4782 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4783
4784 // caller: device admin or delegated certificate installer
4785 callerContext.applicationInfo = new ApplicationInfo();
4786 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4787
4788 // system_server
4789 final DpmMockContext serviceContext = mContext;
4790 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004791 getServices().addPackageContext(callerUser, admin1Context);
4792 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004793
4794 // Install a CA cert.
4795 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004796 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004797 .thenReturn(alias);
4798 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004799 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004800 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004801 });
4802
Pavel Grafov75c0a892017-05-18 17:28:27 +01004803 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4804 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4805 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004806 flushTasks();
4807
Robin Lee2c68dad2017-03-17 12:50:24 +00004808 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4809
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004810 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004811 runAsCaller(admin1Context, dpms, (dpm) -> {
4812 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004813 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004814 ownerInstalledCaCerts.addAll(installedCaCerts);
4815 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004816
4817 // Restarting the DPMS should not lose information.
4818 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004819 runAsCaller(admin1Context, dpms, (dpm) ->
4820 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004821
4822 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004823 runAsCaller(serviceContext, dpms, (dpm) -> {
4824 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004825
Robin Lee2c68dad2017-03-17 12:50:24 +00004826 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004827 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 });
4829
Pavel Grafov75c0a892017-05-18 17:28:27 +01004830 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4831 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4832 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004833 flushTasks();
4834
4835 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4836 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004837 runAsCaller(admin1Context, dpms, (dpm) -> {
4838 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4839 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004840 }
4841
Robin Lee2c68dad2017-03-17 12:50:24 +00004842 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4843 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004844 final String alias = "cert";
4845 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004846
4847 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004848 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004849 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4850 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004851 }
4852 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4853
4854 // caller: device admin or delegated certificate installer
4855 callerContext.applicationInfo = new ApplicationInfo();
4856 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4857
4858 // system_server
4859 final DpmMockContext serviceContext = mContext;
4860 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004861 getServices().addPackageContext(callerUser, admin1Context);
4862 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004863
4864 // Install a CA cert as caller
4865 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004866 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004867 .thenReturn(alias);
4868 assertTrue(dpm.installCaCert(callerName, caCert));
4869 });
4870
4871 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004872 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004873 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004874 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4875 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4876 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004877 flushTasks();
4878
Robin Lee2c68dad2017-03-17 12:50:24 +00004879 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004880 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004881
4882 runAsCaller(serviceContext, dpms, (dpm) -> {
4883 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4884 assertNotNull(ownerInstalledCaCerts);
4885 assertTrue(ownerInstalledCaCerts.isEmpty());
4886 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004887 }
4888
Eran Messeri94d56762017-12-21 20:50:54 +00004889 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4890 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4891 Arrays.sort(gotFlags);
4892 Arrays.sort(expectedFlags);
4893 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4894 }
4895
4896 public void testTranslationOfIdAttestationFlag() {
4897 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4898 int[] correspondingAttUtilsTypes = new int[]{
4899 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4900 AttestationUtils.ID_TYPE_MEID};
4901
4902 // Test translation of zero flags
4903 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4904
4905 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4906 // non-null array
4907 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4908
4909 // Test translation of a single flag
4910 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4911 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4912 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4913
4914 // Test translation of two flags
4915 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4916 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4917 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4918 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4919
4920 // Test translation of all three flags
4921 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4922 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4923 AttestationUtils.ID_TYPE_MEID});
4924 // Test translation of all three flags
4925 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4926 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4927 AttestationUtils.ID_TYPE_MEID});
4928 }
4929
arangelov08d534b2018-01-22 15:20:53 +00004930 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4931 setDeviceOwner();
4932 initializeDpms();
4933 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4934 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4935 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4936 }
4937
4938 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4939 DpmTestUtils.writeInputStreamToFile(
4940 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4941 getDeviceOwnerPoliciesFile());
4942 DpmTestUtils.writeInputStreamToFile(
4943 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4944 getDeviceOwnerFile());
4945 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4946 }
4947
4948 public void testRevertDeviceOwnership_deviceNotMigrated()
4949 throws Exception {
4950 DpmTestUtils.writeInputStreamToFile(
4951 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4952 getDeviceOwnerPoliciesFile());
4953 DpmTestUtils.writeInputStreamToFile(
4954 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4955 getDeviceOwnerFile());
4956 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4957 }
4958
4959 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4960 throws Exception {
4961 DpmTestUtils.writeInputStreamToFile(
4962 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4963 getDeviceOwnerPoliciesFile());
4964 DpmTestUtils.writeInputStreamToFile(
4965 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4966 getDeviceOwnerFile());
4967 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4968 }
4969
4970 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4971 setupProfileOwner();
4972 initializeDpms();
4973 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4974 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4975 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4976 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4977 }
4978
4979 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4980 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4981 UserHandle.USER_SYSTEM);
4982 DpmTestUtils.writeInputStreamToFile(
4983 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4984 getProfileOwnerPoliciesFile());
4985 DpmTestUtils.writeInputStreamToFile(
4986 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
4987 getProfileOwnerFile());
4988 assertProfileOwnershipRevertedWithFakeTransferMetadata();
4989 }
4990
4991 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
4992 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4993 UserHandle.USER_SYSTEM);
4994 DpmTestUtils.writeInputStreamToFile(
4995 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4996 getProfileOwnerPoliciesFile());
4997 DpmTestUtils.writeInputStreamToFile(
4998 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
4999 getProfileOwnerFile());
5000 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5001 }
5002
5003 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5004 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5005 UserHandle.USER_SYSTEM);
5006 DpmTestUtils.writeInputStreamToFile(
5007 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5008 getProfileOwnerPoliciesFile());
5009 DpmTestUtils.writeInputStreamToFile(
5010 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5011 getProfileOwnerFile());
5012 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5013 }
5014
Eran Messeribb271892018-10-17 18:27:50 +01005015 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5016 setupProfileOwner();
5017 configureContextForAccess(mContext, false);
5018
5019 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005020 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005021 }
5022
5023 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5024 setupProfileOwner();
5025 configureContextForAccess(mContext, false);
5026
5027 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005028 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005029 }
5030
5031 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5032 setupProfileOwner();
5033
5034 // This method will throw if the system context could not call
5035 // setProfileOwnerCanAccessDeviceIds successfully.
5036 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5037 }
5038
5039 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5040 when(context.spiedContext.checkCallingPermission(
5041 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5042 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5043 : PackageManager.PERMISSION_DENIED);
5044 }
5045
5046 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5047 setupProfileOwner();
5048
5049 final long ident = mServiceContext.binder.clearCallingIdentity();
5050 configureContextForAccess(mServiceContext, true);
5051
5052 mServiceContext.binder.callingUid =
5053 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5054 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5055 try {
5056 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005057 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005058 });
5059 } finally {
5060 mServiceContext.binder.restoreCallingIdentity(ident);
5061 }
5062 }
5063
5064 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5065 throws Exception {
5066 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5067 setupDeviceOwner();
5068 configureContextForAccess(mContext, false);
5069
5070 // Device owner should be allowed to request Device ID attestation.
5071 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5072 DpmMockContext.CALLER_SYSTEM_USER_UID);
5073
5074 // Another package must not be allowed to request Device ID attestation.
5075 assertExpectException(SecurityException.class, null,
5076 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5077 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5078 // Another component that is not the admin must not be allowed to request Device ID
5079 // attestation.
5080 assertExpectException(SecurityException.class, null,
5081 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5082 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5083 }
5084
5085 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5086 throws Exception {
5087 configureContextForAccess(mContext, false);
5088
5089 // Make sure a security exception is thrown if the device has no profile owner.
5090 assertExpectException(SecurityException.class, null,
5091 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5092 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5093
5094 setupProfileOwner();
5095 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5096
5097 // The profile owner is allowed to request Device ID attestation.
5098 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5099 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5100 DpmMockContext.CALLER_UID);
5101 // But not another package.
5102 assertExpectException(SecurityException.class, null,
5103 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5104 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5105 // Or another component which is not the admin.
5106 assertExpectException(SecurityException.class, null,
5107 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5108 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5109 }
5110
5111 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5112 final long ident = mServiceContext.binder.clearCallingIdentity();
5113
5114 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5115 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5116 try {
5117 runAsCaller(mServiceContext, dpms, action);
5118 } finally {
5119 mServiceContext.binder.restoreCallingIdentity(ident);
5120 }
5121 }
5122
5123 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5124 setupProfileOwner();
5125 markDelegatedCertInstallerAsInstalled();
5126
5127 // Configure a delegated cert installer.
5128 runAsCaller(mServiceContext, dpms,
5129 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5130 Arrays.asList(DELEGATION_CERT_INSTALL)));
5131
5132 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5133
5134 // Make sure that the profile owner can still request Device ID attestation.
5135 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5136 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5137 DpmMockContext.CALLER_UID);
5138
5139 runAsDelegatedCertInstaller(dpm -> {
5140 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5141 DpmMockContext.DELEGATE_PACKAGE_NAME,
5142 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5143 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5144 });
5145 }
5146
5147 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5148 throws Exception {
5149 setupProfileOwner();
5150 markDelegatedCertInstallerAsInstalled();
5151
5152 // Configure a delegated cert installer.
5153 runAsCaller(mServiceContext, dpms,
5154 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5155 Arrays.asList(DELEGATION_CERT_INSTALL)));
5156
5157
5158 assertExpectException(SecurityException.class, null,
5159 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5160 admin1.getPackageName(),
5161 DpmMockContext.CALLER_UID));
5162
5163 runAsDelegatedCertInstaller(dpm -> {
5164 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5165 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5166 DpmMockContext.DELEGATE_PACKAGE_NAME,
5167 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5168 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5169 });
5170 }
5171
Bernard Chaue9586552018-11-29 10:59:31 +00005172 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5173 assertThrows(SecurityException.class,
5174 () -> new DevicePolicyManagerTestable(
5175 mServiceContext,
5176 dpms,
5177 /* parentInstance= */ true)
5178 .getPasswordComplexity());
5179 }
5180
5181 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5182 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5183 .thenReturn(false);
5184 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5185 }
5186
5187 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5188 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5189 .thenReturn(true);
5190 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5191 }
5192
5193
5194 public void testGetPasswordComplexity_currentUserNoPassword() {
5195 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5196 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005197 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005198 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5199 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5200
5201 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5202 }
5203
5204 public void testGetPasswordComplexity_currentUserHasPassword() {
5205 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5206 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005207 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005208 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5209 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5210 dpms.mUserPasswordMetrics.put(
5211 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005212 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005213
5214 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5215 }
5216
5217 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5218 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5219 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005220 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005221
5222 UserInfo parentUser = new UserInfo();
5223 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5224 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5225 .thenReturn(parentUser.id);
5226
5227 dpms.mUserPasswordMetrics.put(
5228 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005229 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005230 dpms.mUserPasswordMetrics.put(
5231 parentUser.id,
Rich Canningsf64ec632019-02-21 12:40:36 -08005232 PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005233
5234 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5235 }
5236
yuemingwd2bfbc82019-01-02 11:42:25 +00005237 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5238 setAsProfileOwner(admin1);
5239 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5240 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5241 }
5242
5243 public void testCrossProfileCalendarPackages_reopenDpms() {
5244 setAsProfileOwner(admin1);
5245 dpm.setCrossProfileCalendarPackages(admin1, null);
5246 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5247 assertTrue(packages == null);
5248 initializeDpms();
5249 packages = dpm.getCrossProfileCalendarPackages(admin1);
5250 assertTrue(packages == null);
5251
5252 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5253 packages = dpm.getCrossProfileCalendarPackages(admin1);
5254 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5255 initializeDpms();
5256 packages = dpm.getCrossProfileCalendarPackages(admin1);
5257 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5258
5259 final String dummyPackageName = "test";
5260 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5261 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5262 packages = dpm.getCrossProfileCalendarPackages(admin1);
5263 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5264 initializeDpms();
5265 packages = dpm.getCrossProfileCalendarPackages(admin1);
5266 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5267 }
5268
5269 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5270 assertTrue(expected != null);
5271 assertTrue(actual != null);
5272 assertTrue(expected.containsAll(actual));
5273 assertTrue(actual.containsAll(expected));
5274 }
5275
yuemingwdded98f2019-01-30 17:08:12 +00005276 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5277 setAsProfileOwner(admin1);
5278 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5279 when(getServices().settings.settingsSecureGetIntForUser(
5280 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5281 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5282 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5283 }
5284
5285 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5286 final String testPackage = "TEST_PACKAGE";
5287 setAsProfileOwner(admin1);
5288 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5289 when(getServices().settings.settingsSecureGetIntForUser(
5290 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5291 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5292 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5293 }
5294
5295 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5296 final String testPackage = "TEST_PACKAGE";
5297 setAsProfileOwner(admin1);
5298 dpm.setCrossProfileCalendarPackages(admin1, null);
5299 when(getServices().settings.settingsSecureGetIntForUser(
5300 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5301 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5302 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5303 }
5304
Eran Messeribb271892018-10-17 18:27:50 +01005305 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5306 final long ident = mServiceContext.binder.clearCallingIdentity();
5307 mServiceContext.binder.callingUid =
5308 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5309 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005310 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005311 });
5312 mServiceContext.binder.restoreCallingIdentity(ident);
5313 }
5314
arangelov08d534b2018-01-22 15:20:53 +00005315 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5316 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5317 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5318 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5319
5320 final long ident = mServiceContext.binder.clearCallingIdentity();
5321 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5322 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5323 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5324 // To simulate a reboot, we just reinitialize dpms and call systemReady
5325 initializeDpms();
5326
5327 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5328 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5329 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5330 assertTrue(dpm.isAdminActive(admin1));
5331 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5332 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5333
5334 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5335 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5336 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5337 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5338
5339 mServiceContext.binder.restoreCallingIdentity(ident);
5340 }
5341
5342 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5343 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5344 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5345 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5346
5347 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5348 DpmMockContext.CALLER_SYSTEM_USER_UID);
5349 setUpPackageManagerForAdmin(admin1, uid);
5350 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5351 // To simulate a reboot, we just reinitialize dpms and call systemReady
5352 initializeDpms();
5353
5354 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5355 assertTrue(dpm.isAdminActive(admin1));
5356 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5357 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5358 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5359 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5360 }
5361
5362 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5363 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5364 metadataManager.deleteMetadataFile();
5365
5366 final TransferOwnershipMetadataManager.Metadata metadata =
5367 new TransferOwnershipMetadataManager.Metadata(
5368 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5369 callerUserHandle,
5370 adminType);
5371 metadataManager.saveMetadataFile(metadata);
5372 }
5373
5374 private File getDeviceOwnerFile() {
5375 return dpms.mOwners.getDeviceOwnerFile();
5376 }
5377
5378 private File getProfileOwnerFile() {
5379 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5380 }
5381
5382 private File getProfileOwnerPoliciesFile() {
5383 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5384 DpmMockContext.CALLER_USER_HANDLE);
5385 return getPoliciesFile(parentDir);
5386 }
5387
5388 private File getDeviceOwnerPoliciesFile() {
5389 return getPoliciesFile(getServices().systemUserDataDir);
5390 }
5391
5392 private File getPoliciesFile(File parentDir) {
5393 return new File(parentDir, "device_policies.xml");
5394 }
5395
5396 private InputStream getRawStream(@RawRes int id) {
5397 return mRealTestContext.getResources().openRawResource(id);
5398 }
5399
Victor Chang3e794af2016-03-04 13:48:17 +00005400 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005401 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005402 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5403 dpms.notifyChangeToContentObserver(
5404 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5405 }
5406
5407 private void assertProvisioningAllowed(String action, boolean expected) {
5408 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5409 dpm.isProvisioningAllowed(action));
5410 }
Tony Mak2f26b792016-11-28 17:54:51 +00005411
Nicolas Prevot45d29072017-01-18 16:11:19 +00005412 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5413 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005414 final String previousPackageName = mContext.packageName;
5415 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005416
5417 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5418 mContext.packageName = packageName;
5419 mMockContext.binder.callingUid = uid;
5420 assertProvisioningAllowed(action, expected);
5421
5422 // Set the previous package name / calling uid to go back to the initial state.
5423 mContext.packageName = previousPackageName;
5424 mMockContext.binder.callingUid = previousUid;
5425 }
5426
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005427 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005428 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5429 }
5430
5431 private void assertCheckProvisioningPreCondition(
5432 String action, String packageName, int provisioningCondition) {
5433 assertEquals("checkProvisioningPreCondition("
5434 + action + ", " + packageName + ") returning unexpected result",
5435 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005436 }
5437
Tony Mak2f26b792016-11-28 17:54:51 +00005438 /**
5439 * Setup a managed profile with the specified admin and its uid.
5440 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5441 * @param adminUid uid of the admin package.
5442 * @param copyFromAdmin package information for {@code admin} will be built based on this
5443 * component's information.
5444 */
5445 private void addManagedProfile(
5446 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5447 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005448 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005449 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5450 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5451 dpm.setActiveAdmin(admin, false, userId);
5452 assertTrue(dpm.setProfileOwner(admin, null, userId));
5453 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5454 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005455
5456 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005457 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005458 */
Robin Leeabaa0692017-02-20 20:54:22 +00005459 private static StringParceledListSlice asSlice(String[] s) {
5460 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005461 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005462
5463 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005464 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5465 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005466
Robin Lee2c68dad2017-03-17 12:50:24 +00005467 // We can't let exceptions happen on the background thread. Throw them here if they happen
5468 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005469 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005470 }
Victor Chang3e794af2016-03-04 13:48:17 +00005471}