blob: 9a1fd9cf0e1225277bbfd1d72fc1d1b0ce468f9c [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;
Rubin Xu19854862019-08-15 16:37:23 +010043import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010044import static org.mockito.Mockito.doAnswer;
45import static org.mockito.Mockito.doReturn;
46import static org.mockito.Mockito.never;
47import static org.mockito.Mockito.nullable;
48import static org.mockito.Mockito.reset;
49import static org.mockito.Mockito.timeout;
50import static org.mockito.Mockito.times;
51import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080052import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010053import static org.mockito.Mockito.verifyZeroInteractions;
54import static org.mockito.Mockito.when;
55import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000056import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010057
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000059import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010061import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000062import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063import android.app.admin.DeviceAdminReceiver;
64import android.app.admin.DevicePolicyManager;
65import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010066import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000069import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000070import android.content.pm.ApplicationInfo;
71import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010073import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000074import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000075import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010076import android.graphics.Color;
77import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080078import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070079import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080080import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070081import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070082import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010083import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080084import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010085import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000086import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000087import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000088import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080089import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010090import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092
Pavel Grafov57f1b662019-03-27 14:55:38 +000093import androidx.test.filters.SmallTest;
94
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010095import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000096import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000097import com.android.server.LocalServices;
98import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000099import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000100import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000101
Robin Lee7f5c91c2017-02-08 21:27:02 +0000102import org.hamcrest.BaseMatcher;
103import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800104import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700105import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106
arangelov08d534b2018-01-22 15:20:53 +0000107import java.io.File;
108import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800109import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000110import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000111import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700112import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700114import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100115import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000116import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700119 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000120 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 m FrameworksServicesTests &&
122 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000123 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700125 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126
127 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000128 *
129 * , or:
130 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000132@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100133@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000135 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
136 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
137 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100138 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800139 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100140 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000141
Pavel Grafov75c0a892017-05-18 17:28:27 +0100142 // TODO replace all instances of this with explicit {@link #mServiceContext}.
143 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700144 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100145
146 private DpmMockContext mServiceContext;
147 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700148 public DevicePolicyManager dpm;
149 public DevicePolicyManagerServiceTestable dpms;
150
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100151 /*
152 * The CA cert below is the content of cacert.pem as generated by:
153 *
154 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
155 */
156 private static final String TEST_CA =
157 "-----BEGIN CERTIFICATE-----\n" +
158 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
159 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
160 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
161 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
162 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
163 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
164 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
165 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
166 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
167 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
168 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
169 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
170 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
171 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
172 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
173 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
174 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
175 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
176 "wQ==\n" +
177 "-----END CERTIFICATE-----\n";
178
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700179 @Override
180 protected void setUp() throws Exception {
181 super.setUp();
182
183 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100184 mServiceContext = mContext;
185 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
186 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100188 doReturn(Collections.singletonList(new ResolveInfo()))
189 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
190 any(Intent.class),
191 anyInt(),
192 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700193
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800194 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800196
Makoto Onukia52562c2015-10-01 16:12:31 -0700197 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700198
Sudheer Shanka101c3532018-01-08 16:28:42 -0800199 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800200 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700201 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
202 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
203 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800204 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700205
Pavel Grafov75c0a892017-05-18 17:28:27 +0100206 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
207 mAdmin1Context.packageName = admin1.getPackageName();
208 mAdmin1Context.applicationInfo = new ApplicationInfo();
209 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
210
Makoto Onukib643fb02015-09-22 15:03:44 -0700211 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100212
213 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700214 }
215
arangelov08d534b2018-01-22 15:20:53 +0000216 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
217 return dpms.mTransferOwnershipMetadataManager;
218 }
219
Robin Lee2c68dad2017-03-17 12:50:24 +0000220 @Override
221 protected void tearDown() throws Exception {
222 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000223 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000224 super.tearDown();
225 }
226
Makoto Onukia52562c2015-10-01 16:12:31 -0700227 private void initializeDpms() {
228 // Need clearCallingIdentity() to pass permission checks.
229 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700231
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
233 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
234 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700239 }
240
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 private void setUpUserManager() {
242 // Emulate UserManager.set/getApplicationRestriction().
243 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
244
245 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000246 doAnswer((Answer<Void>) invocation -> {
247 String pkg = (String) invocation.getArguments()[0];
248 Bundle bundle = (Bundle) invocation.getArguments()[1];
249 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000251 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000253 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100255 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700256
257 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000258 doAnswer((Answer<Bundle>) invocation -> {
259 String pkg = (String) invocation.getArguments()[0];
260 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000262 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100263 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700264 anyString(), any(UserHandle.class));
265
Makoto Onukid932f762015-09-29 16:53:38 -0700266 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700268 }
269
270 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700272
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 mServiceContext.binder.callingUid =
274 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
275 runAsCaller(mServiceContext, dpms, dpm -> {
276 // PO needs to be a DA.
277 dpm.setActiveAdmin(admin, /*replace=*/ false);
278 // Fire!
279 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
280 // Check
281 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
282 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700283
Pavel Grafov75c0a892017-05-18 17:28:27 +0100284 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700285 }
286
287 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100288 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700289 .thenReturn(false);
290
291 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100292 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700293
294 // If the device has no DPMS feature, it shouldn't register the local service.
295 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
296 }
297
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800298 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800299 // Device owner in SYSTEM_USER
300 setDeviceOwner();
301 // Profile owner in CALLER_USER_HANDLE
302 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
303 setAsProfileOwner(admin2);
304 // Active admin in CALLER_USER_HANDLE
305 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
306 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
307 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
308 DpmMockContext.CALLER_USER_HANDLE);
309 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
310 DpmMockContext.CALLER_USER_HANDLE));
311
312 initializeDpms();
313
314 // Verify
315 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800316 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800317 eq(UserHandle.USER_SYSTEM));
318 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800319 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800320 adminAnotherPackage.getPackageName()),
321 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800322 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
323 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
324 }
325
326 public void testLoadAdminData_noAdmins() throws Exception {
327 final int ANOTHER_USER_ID = 15;
328 getServices().addUser(ANOTHER_USER_ID, 0);
329
330 initializeDpms();
331
332 // Verify
333 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
334 null, DpmMockContext.CALLER_USER_HANDLE);
335 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
336 null, ANOTHER_USER_ID);
337 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
338 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800339 }
340
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700341 /**
342 * Caller doesn't have proper permissions.
343 */
344 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700345 // 1. Failure cases.
346
347 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100348 assertExpectException(SecurityException.class, /* messageRegex= */ null,
349 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700350
351 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
352 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100353
354 assertExpectException(SecurityException.class, /* messageRegex= */ null,
355 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700356 }
357
Makoto Onukif76b06a2015-09-22 15:03:44 -0700358 /**
359 * Test for:
360 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800361 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362 * {@link DevicePolicyManager#isAdminActive}
363 * {@link DevicePolicyManager#isAdminActiveAsUser}
364 * {@link DevicePolicyManager#getActiveAdmins}
365 * {@link DevicePolicyManager#getActiveAdminsAsUser}
366 */
367 public void testSetActiveAdmin() throws Exception {
368 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700369 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
370
Makoto Onukif76b06a2015-09-22 15:03:44 -0700371 // 2. Call the API.
372 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373
374 // 3. Verify internal calls.
375
376 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700377 verify(mContext.spiedContext).sendBroadcastAsUser(
378 MockUtils.checkIntentAction(
379 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
380 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
381 verify(mContext.spiedContext).sendBroadcastAsUser(
382 MockUtils.checkIntentAction(
383 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100384 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
385 eq(null),
386 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700387
Pavel Grafov75c0a892017-05-18 17:28:27 +0100388 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389 eq(admin1.getPackageName()),
390 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
391 eq(PackageManager.DONT_KILL_APP),
392 eq(DpmMockContext.CALLER_USER_HANDLE),
393 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394
Sudheer Shanka101c3532018-01-08 16:28:42 -0800395 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
396 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
397
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700398 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700399
400 // Make sure it's active admin1.
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403 assertFalse(dpm.isAdminActive(admin3));
404
405 // But not admin1 for a different user.
406
407 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
408 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
409 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
412 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
413
414 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
415
416 // Next, add one more admin.
417 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700418 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700419 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700420
421 dpm.setActiveAdmin(admin2, /* replace =*/ false);
422
423 // Now we have two admins.
424 assertTrue(dpm.isAdminActive(admin1));
425 assertTrue(dpm.isAdminActive(admin2));
426 assertFalse(dpm.isAdminActive(admin3));
427
428 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
429 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100430 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431 eq(admin1.getPackageName()),
432 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
433 eq(PackageManager.DONT_KILL_APP),
434 eq(DpmMockContext.CALLER_USER_HANDLE),
435 anyString());
436
Sudheer Shanka101c3532018-01-08 16:28:42 -0800437 // times(2) because it was previously called for admin1 which is in the same package
438 // as admin2.
439 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
440 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
441
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100443 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
444 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445
446 // 5. Add the same admin1 again with replace, which should succeed.
447 dpm.setActiveAdmin(admin1, /* replace =*/ true);
448
449 // TODO make sure it's replaced.
450
451 // 6. Test getActiveAdmins()
452 List<ComponentName> admins = dpm.getActiveAdmins();
453 assertEquals(2, admins.size());
454 assertEquals(admin1, admins.get(0));
455 assertEquals(admin2, admins.get(1));
456
Sudheer Shanka101c3532018-01-08 16:28:42 -0800457 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
458 // replaced
459 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
460
Makoto Onukif76b06a2015-09-22 15:03:44 -0700461 // Another user has no admins.
462 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
463
464 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
465 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
466
467 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
468 }
469
Makoto Onukid932f762015-09-29 16:53:38 -0700470 public void testSetActiveAdmin_multiUsers() throws Exception {
471
472 final int ANOTHER_USER_ID = 100;
473 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
474
Pavel Grafov75c0a892017-05-18 17:28:27 +0100475 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 // Set up pacakge manager for the other user.
478 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
481
482 dpm.setActiveAdmin(admin1, /* replace =*/ false);
483
484 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
485 dpm.setActiveAdmin(admin2, /* replace =*/ false);
486
487
488 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
489 assertTrue(dpm.isAdminActive(admin1));
490 assertFalse(dpm.isAdminActive(admin2));
491
492 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
493 assertFalse(dpm.isAdminActive(admin1));
494 assertTrue(dpm.isAdminActive(admin2));
495 }
496
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 /**
498 * Test for:
499 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800500 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700501 */
502 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
503 // 1. Make sure the caller has proper permissions.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506 dpm.setActiveAdmin(admin1, /* replace =*/ false);
507 assertTrue(dpm.isAdminActive(admin1));
508
509 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
511 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700512 }
513
514 /**
515 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800516 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
517 * BIND_DEVICE_ADMIN.
518 */
519 public void testSetActiveAdmin_permissionCheck() throws Exception {
520 // 1. Make sure the caller has proper permissions.
521 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
522
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(IllegalArgumentException.class,
524 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
525 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800526 assertFalse(dpm.isAdminActive(adminNoPerm));
527
528 // Change the target API level to MNC. Now it can be set as DA.
529 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
530 VERSION_CODES.M);
531 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
532 assertTrue(dpm.isAdminActive(adminNoPerm));
533
534 // TODO Test the "load from the file" case where DA will still be loaded even without
535 // BIND_DEVICE_ADMIN and target API is N.
536 }
537
538 /**
539 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700540 * {@link DevicePolicyManager#removeActiveAdmin}
541 */
542 public void testRemoveActiveAdmin_SecurityException() {
543 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
544
545 // Add admin.
546
547 dpm.setActiveAdmin(admin1, /* replace =*/ false);
548
549 assertTrue(dpm.isAdminActive(admin1));
550
551 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
552
553 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100554 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
555 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700556
557 // Try to remove active admin with a different caller userid should fail too, without
558 // having MANAGE_DEVICE_ADMINS.
559 mContext.callerPermissions.clear();
560
Makoto Onukid932f762015-09-29 16:53:38 -0700561 // Change the caller, and call into DPMS directly with a different user-id.
562
Makoto Onukif76b06a2015-09-22 15:03:44 -0700563 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100564 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
565 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 }
567
568 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800569 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
570 * (because we can't send the remove broadcast).
571 */
572 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
573 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
574
575 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
576
577 // Add admin.
578
579 dpm.setActiveAdmin(admin1, /* replace =*/ false);
580
581 assertTrue(dpm.isAdminActive(admin1));
582
583 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
584
585 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100586 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100588 assertExpectException(IllegalStateException.class,
589 /* messageRegex= */ "User must be running and unlocked",
590 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800593 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
594 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800595
596 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100597 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598 .thenReturn(true);
599
600 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700601 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800602 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
603 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800604 }
605
606 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 * Test for:
608 * {@link DevicePolicyManager#removeActiveAdmin}
609 */
Makoto Onukid932f762015-09-29 16:53:38 -0700610 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700611 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
612
613 // Add admin1.
614
615 dpm.setActiveAdmin(admin1, /* replace =*/ false);
616
617 assertTrue(dpm.isAdminActive(admin1));
618 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
619
620 // Different user, but should work, because caller has proper permissions.
621 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700622
623 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700624 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700627 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800628 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
629 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700630
631 // TODO DO Still can't be removed in this case.
632 }
633
634 /**
635 * Test for:
636 * {@link DevicePolicyManager#removeActiveAdmin}
637 */
638 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
639 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
640 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
641
642 // Add admin1.
643
644 dpm.setActiveAdmin(admin1, /* replace =*/ false);
645
646 assertTrue(dpm.isAdminActive(admin1));
647 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
648
649 // Broadcast from saveSettingsLocked().
650 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
651 MockUtils.checkIntentAction(
652 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
653 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
654
655 // Remove. No permissions, but same user, so it'll work.
656 mContext.callerPermissions.clear();
657 dpm.removeActiveAdmin(admin1);
658
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
660 MockUtils.checkIntentAction(
661 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
662 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
663 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100664 eq(AppOpsManager.OP_NONE),
665 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700667 eq(dpms.mHandler),
668 eq(Activity.RESULT_OK),
669 isNull(String.class),
670 isNull(Bundle.class));
671
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700672 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800673 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
674 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700675
676 // Again broadcast from saveSettingsLocked().
677 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
678 MockUtils.checkIntentAction(
679 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
680 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
681
682 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700683 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700684
Sudheer Shanka101c3532018-01-08 16:28:42 -0800685 public void testRemoveActiveAdmin_multipleAdminsInUser() {
686 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
687 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
688
689 // Add admin1.
690 dpm.setActiveAdmin(admin1, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin1));
693 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Add admin2.
696 dpm.setActiveAdmin(admin2, /* replace =*/ false);
697
698 assertTrue(dpm.isAdminActive(admin2));
699 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
700
701 // Broadcast from saveSettingsLocked().
702 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
703 MockUtils.checkIntentAction(
704 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
705 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
706
707 // Remove. No permissions, but same user, so it'll work.
708 mContext.callerPermissions.clear();
709 dpm.removeActiveAdmin(admin1);
710
711 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
712 MockUtils.checkIntentAction(
713 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
714 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
715 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100716 eq(AppOpsManager.OP_NONE),
717 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800718 any(BroadcastReceiver.class),
719 eq(dpms.mHandler),
720 eq(Activity.RESULT_OK),
721 isNull(String.class),
722 isNull(Bundle.class));
723
724 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
725 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800726 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800727 eq(DpmMockContext.CALLER_USER_HANDLE));
728
729 // Again broadcast from saveSettingsLocked().
730 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
731 MockUtils.checkIntentAction(
732 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
733 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
734 }
735
736 /**
737 * Test for:
738 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
739 */
740 public void testForceRemoveActiveAdmin() throws Exception {
741 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
742
743 // Add admin.
744 setupPackageInPackageManager(admin1.getPackageName(),
745 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
746 /* appId= */ 10138,
747 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
748 dpm.setActiveAdmin(admin1, /* replace =*/ false);
749 assertTrue(dpm.isAdminActive(admin1));
750
751 // Calling from a non-shell uid should fail with a SecurityException
752 mContext.binder.callingUid = 123456;
753 assertExpectException(SecurityException.class,
754 /* messageRegex =*/ "Non-shell user attempted to call",
755 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
756
757 mContext.binder.callingUid = Process.SHELL_UID;
758 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
759
760 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
761 // Verify
762 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
763 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
764 null, DpmMockContext.CALLER_USER_HANDLE);
765 }
766
Makoto Onukib643fb02015-09-22 15:03:44 -0700767 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100768 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
769 *
770 * Validates that when the password history length is set, it is persisted after rebooting
771 */
772 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
773 int passwordHistoryLength = 2;
774
775 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
777 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
778
779 // Install admin1 on system user.
780 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
781
782 // Set admin1 to active admin and device owner
783 dpm.setActiveAdmin(admin1, false);
784 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
785
786 // Save password history length
787 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
788
789 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
790
791 initializeDpms();
792 reset(mContext.spiedContext);
793
794 // Password history length should persist after rebooted
795 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
796 }
797
798 /**
799 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000800 *
801 * Validates that when the password for a user changes, the notification broadcast intent
802 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
803 * addition to ones in the original user.
804 */
805 public void testSetActivePasswordState_sendToProfiles() throws Exception {
806 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
807
808 final int MANAGED_PROFILE_USER_ID = 78;
809 final int MANAGED_PROFILE_ADMIN_UID =
810 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
811
812 // Setup device owner.
813 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
814 mContext.packageName = admin1.getPackageName();
815 setupDeviceOwner();
816
817 // Add a managed profile belonging to the system user.
818 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
819
820 // Change the parent user's password.
821 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
822
823 // Both the device owner and the managed profile owner should receive this broadcast.
824 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
825 intent.setComponent(admin1);
826 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
827
828 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
829 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100830 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
831 eq(null),
832 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000833 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
834 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100835 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
836 eq(null),
837 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000838 }
839
840 /**
Rubin Xu19854862019-08-15 16:37:23 +0100841 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000842 *
843 * Validates that when the password for a managed profile changes, the notification broadcast
844 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
845 * its parent.
846 */
847 public void testSetActivePasswordState_notSentToParent() throws Exception {
848 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
849
850 final int MANAGED_PROFILE_USER_ID = 78;
851 final int MANAGED_PROFILE_ADMIN_UID =
852 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
853
854 // Setup device owner.
855 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
856 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100857 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000858 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
859 setupDeviceOwner();
860
861 // Add a managed profile belonging to the system user.
862 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
863
864 // Change the profile's password.
865 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
866
867 // Both the device owner and the managed profile owner should receive this broadcast.
868 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
869 intent.setComponent(admin1);
870 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
871
872 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
873 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100874 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
875 eq(null),
876 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000877 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
878 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100879 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
880 eq(null),
881 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000882 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100883
Robin Leed2a73ed2016-12-19 09:07:16 +0000884 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000885 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700886 */
887 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000888 setDeviceOwner();
889
890 // Try to set a profile owner on the same user, which should fail.
891 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
892 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100893 assertExpectException(IllegalStateException.class,
894 /* messageRegex= */ "already has a device owner",
895 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000896
897 // DO admin can't be deactivated.
898 dpm.removeActiveAdmin(admin1);
899 assertTrue(dpm.isAdminActive(admin1));
900
901 // TODO Test getDeviceOwnerName() too. To do so, we need to change
902 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
903 }
904
905 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800907 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700908 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
909 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
910
Makoto Onukid932f762015-09-29 16:53:38 -0700911 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700912 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
913
Makoto Onukid932f762015-09-29 16:53:38 -0700914 // Make sure admin1 is installed on system user.
915 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700916
Makoto Onukic8a5a552015-11-19 14:29:12 -0800917 // Check various get APIs.
918 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
919
Makoto Onukib643fb02015-09-22 15:03:44 -0700920 // DO needs to be an DA.
921 dpm.setActiveAdmin(admin1, /* replace =*/ false);
922
923 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700924 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700925
Makoto Onukic8a5a552015-11-19 14:29:12 -0800926 // getDeviceOwnerComponent should return the admin1 component.
927 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
928 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
929
930 // Check various get APIs.
931 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
932
933 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
934 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
935 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
936 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
937
938 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
939
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000940 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100941 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000942 eq(admin1.getPackageName()));
943
Makoto Onukib643fb02015-09-22 15:03:44 -0700944 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100945 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700946 eq(UserHandle.USER_SYSTEM), eq(false));
947
948 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
949 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
951
Makoto Onukic8a5a552015-11-19 14:29:12 -0800952 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700953 }
954
Makoto Onukic8a5a552015-11-19 14:29:12 -0800955 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
956 final int origCallingUser = mContext.binder.callingUid;
957 final List origPermissions = new ArrayList(mContext.callerPermissions);
958 mContext.callerPermissions.clear();
959
960 mContext.callerPermissions.add(permission.MANAGE_USERS);
961
962 mContext.binder.callingUid = Process.SYSTEM_UID;
963
964 // TODO Test getDeviceOwnerName() too. To do so, we need to change
965 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
966 if (hasDeviceOwner) {
967 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
968 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
970
971 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
972 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
973 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
974 } else {
975 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
976 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
977 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
978
979 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
982 }
983
984 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
985 if (hasDeviceOwner) {
986 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
987 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
989
990 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
991 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
992 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
993 } else {
994 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
995 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
996 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
997
998 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
999 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1000 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1001 }
1002
1003 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1004 // Still with MANAGE_USERS.
1005 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1006 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1007 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1008
1009 if (hasDeviceOwner) {
1010 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1011 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1012 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1013 } else {
1014 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1015 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1016 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1017 }
1018
1019 mContext.binder.callingUid = Process.SYSTEM_UID;
1020 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1021 // System can still call "OnAnyUser" without MANAGE_USERS.
1022 if (hasDeviceOwner) {
1023 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1024 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1025 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1026
1027 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1028 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1029 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1030 } else {
1031 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1032 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1033 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1034
1035 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1036 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1037 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1038 }
1039
1040 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1041 // Still no MANAGE_USERS.
1042 if (hasDeviceOwner) {
1043 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1044 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1045 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1046 } else {
1047 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1048 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1049 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1050 }
1051
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001052 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1053 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1054 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1055 dpm::getDeviceOwnerComponentOnAnyUser);
1056 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1057 dpm::getDeviceOwnerUserId);
1058 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1059 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001060
1061 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1062 // Still no MANAGE_USERS.
1063 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1064 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1065 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1066
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001067 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1068 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1069 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1070 dpm::getDeviceOwnerComponentOnAnyUser);
1071 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1072 dpm::getDeviceOwnerUserId);
1073 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1074 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001075
1076 // Restore.
1077 mContext.binder.callingUid = origCallingUser;
1078 mContext.callerPermissions.addAll(origPermissions);
1079 }
1080
1081
Makoto Onukib643fb02015-09-22 15:03:44 -07001082 /**
1083 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1084 */
1085 public void testSetDeviceOwner_noSuchPackage() {
1086 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001087 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001088 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1089 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1090
1091 // Call from a process on the system user.
1092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1093
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001094 assertExpectException(IllegalArgumentException.class,
1095 /* messageRegex= */ "Invalid component",
1096 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001097 }
1098
1099 public void testSetDeviceOwner_failures() throws Exception {
1100 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1101 }
1102
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 public void testClearDeviceOwner() throws Exception {
1104 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001105 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001106 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1107 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1108
1109 // Set admin1 as a DA to the secondary user.
1110 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1111
1112 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1113
1114 // Set admin 1 as the DO to the system user.
1115
1116 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1117 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1118 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1119 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1120
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001121 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001122 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001123 eq(admin1.getPackageName()));
1124
Makoto Onukic8a5a552015-11-19 14:29:12 -08001125 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001126
Makoto Onuki90b89652016-01-28 14:44:18 -08001127 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001128 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001129 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001130
1131 assertTrue(dpm.isAdminActive(admin1));
1132 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1133
Makoto Onukia52562c2015-10-01 16:12:31 -07001134 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001135 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001136
1137 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001138 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1139 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001140
1141 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001142 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001143 assertExpectException(IllegalStateException.class,
1144 /* messageRegex= */ "User must be running and unlocked",
1145 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001146
Pavel Grafov75c0a892017-05-18 17:28:27 +01001147 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1148 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001149 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1150
1151 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001152 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001153
Pavel Grafov75c0a892017-05-18 17:28:27 +01001154 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001155 eq(false),
1156 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1157
Pavel Grafov75c0a892017-05-18 17:28:27 +01001158 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001159 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001160 eq(null),
1161 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001162
Sudheer Shanka101c3532018-01-08 16:28:42 -08001163 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1164 null, UserHandle.USER_SYSTEM);
1165
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001166 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001167
1168 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1169 // and once for clearing it.
1170 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1171 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1172 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001173 // TODO Check other calls.
1174 }
1175
1176 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1177 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001178 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1180 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1181
1182 // Set admin1 as a DA to the secondary user.
1183 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1184
1185 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1186
1187 // Set admin 1 as the DO to the system user.
1188
1189 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1190 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1191 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1192 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1193
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001194 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001196 eq(admin1.getPackageName()));
1197
Makoto Onukic8a5a552015-11-19 14:29:12 -08001198 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001199
1200 // Now call clear from the secondary user, which should throw.
1201 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1202
1203 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001204 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001205 eq(admin1.getPackageName()),
1206 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001207 assertExpectException(SecurityException.class,
1208 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1209 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001210
Makoto Onukic8a5a552015-11-19 14:29:12 -08001211 // DO shouldn't be removed.
1212 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001213 }
1214
Alex Johnston63220932019-09-26 10:10:51 +01001215 /**
1216 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1217 *
1218 * Validates that when the device owner is removed, the reset password token is cleared
1219 */
1220 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1221 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1222 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1223 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1224
1225 // Install admin1 on system user
1226 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1227
1228 // Set admin1 to active admin and device owner
1229 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1230 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1231
1232 // Add reset password token
1233 final long handle = 12000;
1234 final byte[] token = new byte[32];
1235 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1236 nullable(EscrowTokenStateChangeCallback.class)))
1237 .thenReturn(handle);
1238 assertTrue(dpm.setResetPasswordToken(admin1, token));
1239
1240 // Assert reset password token is active
1241 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1242 eq(UserHandle.USER_SYSTEM)))
1243 .thenReturn(true);
1244 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1245
1246 // Remove the device owner
1247 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1248
1249 // Verify password reset password token was removed
1250 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1251 eq(UserHandle.USER_SYSTEM));
1252 }
1253
Makoto Onukib643fb02015-09-22 15:03:44 -07001254 public void testSetProfileOwner() throws Exception {
1255 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001256
Makoto Onuki90b89652016-01-28 14:44:18 -08001257 // PO admin can't be deactivated.
1258 dpm.removeActiveAdmin(admin1);
1259 assertTrue(dpm.isAdminActive(admin1));
1260
Makoto Onuki803d6752015-10-30 12:58:39 -07001261 // Try setting DO on the same user, which should fail.
1262 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001263 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1264 runAsCaller(mServiceContext, dpms, dpm -> {
1265 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001266 assertExpectException(IllegalStateException.class,
1267 /* messageRegex= */ "already has a profile owner",
1268 () -> dpm.setDeviceOwner(admin2, "owner-name",
1269 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001270 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001271 }
1272
Makoto Onuki90b89652016-01-28 14:44:18 -08001273 public void testClearProfileOwner() throws Exception {
1274 setAsProfileOwner(admin1);
1275
1276 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1277
1278 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1279 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1280
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001281 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001282 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001283 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001284 assertExpectException(IllegalStateException.class,
1285 /* messageRegex= */ "User must be running and unlocked",
1286 () -> dpm.clearProfileOwner(admin1));
1287
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001288 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001289 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001290 dpm.clearProfileOwner(admin1);
1291
1292 // Check
1293 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001294 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001295 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1296 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001297 }
1298
Makoto Onukib643fb02015-09-22 15:03:44 -07001299 public void testSetProfileOwner_failures() throws Exception {
1300 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1301 }
1302
Makoto Onukia52562c2015-10-01 16:12:31 -07001303 public void testGetDeviceOwnerAdminLocked() throws Exception {
1304 checkDeviceOwnerWithMultipleDeviceAdmins();
1305 }
1306
1307 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1308 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1309 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1310 // make sure it gets the right component from the right user.
1311
1312 final int ANOTHER_USER_ID = 100;
1313 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1314
Pavel Grafov75c0a892017-05-18 17:28:27 +01001315 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001316
1317 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001318 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001319 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1320 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1321
1322 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1323
Pavel Grafov75c0a892017-05-18 17:28:27 +01001324 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001325
Makoto Onukia52562c2015-10-01 16:12:31 -07001326 // Make sure the admin packge is installed to each user.
1327 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1328 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1329
1330 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1331 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1332
1333 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1334
1335
1336 // Set active admins to the users.
1337 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1338 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1339
1340 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1341 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1342
1343 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1344
1345 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001346 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001347 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1348
Makoto Onukic8a5a552015-11-19 14:29:12 -08001349 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001350
1351 // Then check getDeviceOwnerAdminLocked().
1352 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1353 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1354 }
1355
1356 /**
1357 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001358 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1359 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001360 *
1361 * We didn't use to persist the DO component class name, but now we do, and the above method
1362 * finds the right component from a package name upon migration.
1363 */
1364 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001365 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001366 checkDeviceOwnerWithMultipleDeviceAdmins();
1367
1368 // Overwrite the device owner setting and clears the clas name.
1369 dpms.mOwners.setDeviceOwner(
1370 new ComponentName(admin2.getPackageName(), ""),
1371 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1372 dpms.mOwners.writeDeviceOwner();
1373
1374 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001375 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001376
1377 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001378 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001379 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001380 initializeDpms();
1381
1382 // Now the DO component name is a full name.
1383 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1384 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001385 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001386 }
1387
Makoto Onukib643fb02015-09-22 15:03:44 -07001388 public void testSetGetApplicationRestriction() {
1389 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001390 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001391
1392 {
1393 Bundle rest = new Bundle();
1394 rest.putString("KEY_STRING", "Foo1");
1395 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1396 }
1397
1398 {
1399 Bundle rest = new Bundle();
1400 rest.putString("KEY_STRING", "Foo2");
1401 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1402 }
1403
1404 {
1405 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1406 assertNotNull(returned);
1407 assertEquals(returned.size(), 1);
1408 assertEquals(returned.get("KEY_STRING"), "Foo1");
1409 }
1410
1411 {
1412 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1413 assertNotNull(returned);
1414 assertEquals(returned.size(), 1);
1415 assertEquals(returned.get("KEY_STRING"), "Foo2");
1416 }
1417
1418 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1419 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1420 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001421
Edman Anjosf9946772016-11-28 16:35:15 +01001422 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001423 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1424 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001425 *
1426 * @param packageName the name of the package to be setup
1427 * @param appId the application ID to be given to the package
1428 * @return the UID of the package as known by the mock package manager
1429 */
1430 private int setupPackageInPackageManager(final String packageName, final int appId)
1431 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001432 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001433 ApplicationInfo.FLAG_HAS_CODE);
1434 }
1435
1436 /**
1437 * Setup a package in the package manager mock. Useful for faking installed applications.
1438 *
1439 * @param packageName the name of the package to be setup
1440 * @param userId the user id where the package will be "installed"
1441 * @param appId the application ID to be given to the package
1442 * @param flags flags to set in the ApplicationInfo for this package
1443 * @return the UID of the package as known by the mock package manager
1444 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001445 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1446 int flags) throws Exception {
1447 final int uid = UserHandle.getUid(userId, appId);
1448 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001449 final PackageInfo pi = new PackageInfo();
1450 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001451 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001452 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001453 eq(packageName),
1454 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001455 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001456 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001457 eq(packageName),
1458 anyInt(),
1459 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001460 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001461 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001462 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001463 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001464 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001465 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001466 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001467 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001468 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001469 return uid;
1470 }
1471
Robin Lee7f5c91c2017-02-08 21:27:02 +00001472 public void testCertificateDisclosure() throws Exception {
1473 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1474 final UserHandle user = UserHandle.of(userId);
1475
1476 mContext.applicationInfo = new ApplicationInfo();
1477 mContext.callerPermissions.add(permission.MANAGE_USERS);
1478 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001479 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001480 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1481
Robin Leeabaa0692017-02-20 20:54:22 +00001482 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1483 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001484
1485 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1486 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1487
1488 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001489 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001490 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001491 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001492 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001493 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001494 .cancelAsUser(anyString(), anyInt(), eq(user));
1495
1496 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001497 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001498 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001499 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1500 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001501 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001502 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001503 .notifyAsUser(anyString(), anyInt(), argThat(
1504 new BaseMatcher<Notification>() {
1505 @Override
1506 public boolean matches(Object item) {
1507 final Notification noti = (Notification) item;
1508 return TEST_STRING.equals(
1509 noti.extras.getString(Notification.EXTRA_TITLE));
1510 }
1511 @Override
1512 public void describeTo(Description description) {
1513 description.appendText(
1514 "Notification{title=\"" + TEST_STRING + "\"}");
1515 }
1516 }), eq(user));
1517 }
1518
Edman Anjosf9946772016-11-28 16:35:15 +01001519 /**
1520 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1521 * privileges can acually be exercised by a delegate are not covered here.
1522 */
1523 public void testDelegation() throws Exception {
1524 setAsProfileOwner(admin1);
1525
1526 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1527
1528 // Given two packages
1529 final String CERT_DELEGATE = "com.delegate.certs";
1530 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1531 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1532 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1533 20989);
1534
1535 // On delegation
1536 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1537 mContext.packageName = admin1.getPackageName();
1538 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1539 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1540
1541 // DPMS correctly stores and retrieves the delegates
1542 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1543 assertEquals(2, policy.mDelegationMap.size());
1544 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1545 DELEGATION_CERT_INSTALL);
1546 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1547 DELEGATION_CERT_INSTALL);
1548 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1549 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1550 DELEGATION_APP_RESTRICTIONS);
1551 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1552 DELEGATION_APP_RESTRICTIONS);
1553 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1554
1555 // On calling install certificate APIs from an unauthorized process
1556 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1557 mContext.packageName = RESTRICTIONS_DELEGATE;
1558
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001559 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1560 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001561
1562 // On calling install certificate APIs from an authorized process
1563 mContext.binder.callingUid = CERT_DELEGATE_UID;
1564 mContext.packageName = CERT_DELEGATE;
1565
1566 // DPMS executes without a SecurityException
1567 try {
1568 dpm.installCaCert(null, null);
1569 } catch (SecurityException unexpected) {
1570 fail("Threw SecurityException on authorized access");
1571 } catch (NullPointerException expected) {
1572 }
1573
1574 // On removing a delegate
1575 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1576 mContext.packageName = admin1.getPackageName();
1577 dpm.setCertInstallerPackage(admin1, null);
1578
1579 // DPMS does not allow access to ex-delegate
1580 mContext.binder.callingUid = CERT_DELEGATE_UID;
1581 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001582 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1583 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001584
1585 // But still allows access to other existing delegates
1586 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1587 mContext.packageName = RESTRICTIONS_DELEGATE;
1588 try {
1589 dpm.getApplicationRestrictions(null, "pkg");
1590 } catch (SecurityException expected) {
1591 fail("Threw SecurityException on authorized access");
1592 }
1593 }
1594
Esteban Talaverabf60f722015-12-10 16:26:44 +00001595 public void testApplicationRestrictionsManagingApp() throws Exception {
1596 setAsProfileOwner(admin1);
1597
Rubin Xued1928a2016-02-11 17:23:06 +00001598 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001599 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001600 final String nonDelegateExceptionMessageRegex =
1601 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001602 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001603 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1604 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001605
Esteban Talaverabf60f722015-12-10 16:26:44 +00001606 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1607 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001608 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1609 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001610 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001611 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001612 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001613 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1614 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001615
1616 // Check via the profile owner that no restrictions were set.
1617 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001618 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001619 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1620
Rubin Xued1928a2016-02-11 17:23:06 +00001621 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001622 assertExpectException(PackageManager.NameNotFoundException.class,
1623 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1624 () -> dpm.setApplicationRestrictionsManagingPackage(
1625 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001626
Esteban Talaverabf60f722015-12-10 16:26:44 +00001627 // Let appRestrictionsManagerPackage manage app restrictions
1628 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1629 assertEquals(appRestrictionsManagerPackage,
1630 dpm.getApplicationRestrictionsManagingPackage(admin1));
1631
1632 // Now that package should be able to set and retrieve app restrictions.
1633 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001634 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001635 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1636 dpm.setApplicationRestrictions(null, "pkg1", rest);
1637 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1638 assertEquals(1, returned.size(), 1);
1639 assertEquals("Foo1", returned.get("KEY_STRING"));
1640
1641 // The same app running on a separate user shouldn't be able to manage app restrictions.
1642 mContext.binder.callingUid = UserHandle.getUid(
1643 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1644 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001645 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1646 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001647
1648 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1649 // too.
1650 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001651 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001652 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1653 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1654 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1655
1656 // Removing the ability for the package to manage app restrictions.
1657 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1658 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1659 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001660 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001661 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001662 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1663 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001664 }
1665
Makoto Onukia4f11972015-10-01 13:19:58 -07001666 public void testSetUserRestriction_asDo() throws Exception {
1667 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001668 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001669 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1670 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1671
1672 // First, set DO.
1673
1674 // Call from a process on the system user.
1675 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1676
1677 // Make sure admin1 is installed on system user.
1678 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001679
1680 // Call.
1681 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001682 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001683 UserHandle.USER_SYSTEM));
1684
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001685 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001686 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001687 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001688 DpmTestUtils.assertRestrictions(
1689 DpmTestUtils.newRestrictions(defaultRestrictions),
1690 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1691 );
1692 DpmTestUtils.assertRestrictions(
1693 DpmTestUtils.newRestrictions(defaultRestrictions),
1694 dpm.getUserRestrictions(admin1)
1695 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001697 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001698 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001699 eq(true) /* isDeviceOwner */,
1700 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001701 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001702 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001703
1704 for (String restriction : defaultRestrictions) {
1705 dpm.clearUserRestriction(admin1, restriction);
1706 }
1707
Esteban Talavera548a04b2016-12-20 15:22:30 +00001708 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710
1711 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001712 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001713 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001714 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1715 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717
Makoto Onukia4f11972015-10-01 13:19:58 -07001718 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001719 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001720 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001721 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1722 UserManager.DISALLOW_ADD_USER),
1723 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001725
Makoto Onuki068c54a2015-10-13 14:34:03 -07001726 DpmTestUtils.assertRestrictions(
1727 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001729 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1730 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001731 DpmTestUtils.assertRestrictions(
1732 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001733 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001734 dpm.getUserRestrictions(admin1)
1735 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001736
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001738 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 eq(UserHandle.USER_SYSTEM),
1740 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001741 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001743
Makoto Onuki068c54a2015-10-13 14:34:03 -07001744 DpmTestUtils.assertRestrictions(
1745 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1746 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1747 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001748 DpmTestUtils.assertRestrictions(
1749 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1750 dpm.getUserRestrictions(admin1)
1751 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001752
1753 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001754 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755 eq(UserHandle.USER_SYSTEM),
1756 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001757 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001758 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001759
Esteban Talavera548a04b2016-12-20 15:22:30 +00001760 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001761
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001762 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1763 // DO sets them, the scope is global.
1764 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001765 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001766 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001767 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001770 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1771 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001773
1774 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1775 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001776 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001777
1778 // More tests.
1779 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001780 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001782 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1783 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001784 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001785
1786 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001789 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001790 UserManager.DISALLOW_ADD_USER),
1791 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001792 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001793
1794 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001795 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796 eq(UserHandle.USER_SYSTEM),
1797 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001799 UserManager.DISALLOW_ADD_USER),
1800 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001801 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001802 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803
Eric Sandnessca5969d2018-08-10 13:28:46 +01001804 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1805 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1806 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807
Eric Sandnessca5969d2018-08-10 13:28:46 +01001808 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1809 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810
Eric Sandnessca5969d2018-08-10 13:28:46 +01001811 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1812 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1813 () -> dpm.setCameraDisabled(admin1, true));
1814 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1815
1816 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1817 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1818 () -> dpm.setKeyguardDisabledFeatures(admin1,
1819 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1820 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1821
1822 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1823 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1824 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1825 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1826
1827 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1828 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1829 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1830 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001831 }
1832
1833 public void testSetUserRestriction_asPo() {
1834 setAsProfileOwner(admin1);
1835
Makoto Onuki068c54a2015-10-13 14:34:03 -07001836 DpmTestUtils.assertRestrictions(
1837 DpmTestUtils.newRestrictions(),
1838 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1839 .ensureUserRestrictions()
1840 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001841
1842 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001843 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 eq(DpmMockContext.CALLER_USER_HANDLE),
1845 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001846 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001847 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001848
Makoto Onukia4f11972015-10-01 13:19:58 -07001849 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001850 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851 eq(DpmMockContext.CALLER_USER_HANDLE),
1852 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1853 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001854 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001855 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001856
Makoto Onuki068c54a2015-10-13 14:34:03 -07001857 DpmTestUtils.assertRestrictions(
1858 DpmTestUtils.newRestrictions(
1859 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1860 UserManager.DISALLOW_OUTGOING_CALLS
1861 ),
1862 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1863 .ensureUserRestrictions()
1864 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001865 DpmTestUtils.assertRestrictions(
1866 DpmTestUtils.newRestrictions(
1867 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1868 UserManager.DISALLOW_OUTGOING_CALLS
1869 ),
1870 dpm.getUserRestrictions(admin1)
1871 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001872
1873 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001874 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001875 eq(DpmMockContext.CALLER_USER_HANDLE),
1876 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001877 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001878 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001879
1880 DpmTestUtils.assertRestrictions(
1881 DpmTestUtils.newRestrictions(
1882 UserManager.DISALLOW_OUTGOING_CALLS
1883 ),
1884 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1885 .ensureUserRestrictions()
1886 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001887 DpmTestUtils.assertRestrictions(
1888 DpmTestUtils.newRestrictions(
1889 UserManager.DISALLOW_OUTGOING_CALLS
1890 ),
1891 dpm.getUserRestrictions(admin1)
1892 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001893
1894 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001895 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001896 eq(DpmMockContext.CALLER_USER_HANDLE),
1897 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001898 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001899 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001900
Makoto Onuki068c54a2015-10-13 14:34:03 -07001901 DpmTestUtils.assertRestrictions(
1902 DpmTestUtils.newRestrictions(),
1903 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1904 .ensureUserRestrictions()
1905 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001906 DpmTestUtils.assertRestrictions(
1907 DpmTestUtils.newRestrictions(),
1908 dpm.getUserRestrictions(admin1)
1909 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001910
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001911 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1912 // though when DO sets them they'll be applied globally.
1913 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001914 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001915 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001916 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001917 eq(DpmMockContext.CALLER_USER_HANDLE),
1918 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1919 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001920 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001921 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001922
1923 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001924 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001925 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001926 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001927 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001928 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001929 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001930
Makoto Onukia4f11972015-10-01 13:19:58 -07001931 // TODO Make sure restrictions are written to the file.
1932 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001933
Esteban Talavera548a04b2016-12-20 15:22:30 +00001934
1935 public void testDefaultEnabledUserRestrictions() throws Exception {
1936 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1937 mContext.callerPermissions.add(permission.MANAGE_USERS);
1938 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1939 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1940
1941 // First, set DO.
1942
1943 // Call from a process on the system user.
1944 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1945
1946 // Make sure admin1 is installed on system user.
1947 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1948
1949 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1950 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1951 UserHandle.USER_SYSTEM));
1952
1953 // Check that the user restrictions that are enabled by default are set. Then unset them.
1954 String[] defaultRestrictions = UserRestrictionsUtils
1955 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1956 assertTrue(defaultRestrictions.length > 0);
1957 DpmTestUtils.assertRestrictions(
1958 DpmTestUtils.newRestrictions(defaultRestrictions),
1959 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1960 );
1961 DpmTestUtils.assertRestrictions(
1962 DpmTestUtils.newRestrictions(defaultRestrictions),
1963 dpm.getUserRestrictions(admin1)
1964 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001965 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001966 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001967 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001968 eq(true) /* isDeviceOwner */,
1969 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001970 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001971 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001972
1973 for (String restriction : defaultRestrictions) {
1974 dpm.clearUserRestriction(admin1, restriction);
1975 }
1976
1977 assertNoDeviceOwnerRestrictions();
1978
1979 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001980 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001981 initializeDpms();
1982 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1983 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1984
1985 assertNoDeviceOwnerRestrictions();
1986
1987 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1988 // is set as it wasn't enabled during setDeviceOwner.
1989 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1990 assertFalse(UserRestrictionsUtils
1991 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1992 UserRestrictionsUtils
1993 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1994 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001995 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001996 initializeDpms();
1997 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1998 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1999
2000 DpmTestUtils.assertRestrictions(
2001 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2002 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2003 );
2004 DpmTestUtils.assertRestrictions(
2005 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2006 dpm.getUserRestrictions(admin1)
2007 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002008 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00002009 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00002010 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01002011 eq(true) /* isDeviceOwner */,
2012 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002013 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002014 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002015
2016 // Remove the restriction.
2017 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
2018
2019 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
2020 initializeDpms();
2021 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2022 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2023 assertNoDeviceOwnerRestrictions();
2024 } finally {
2025 UserRestrictionsUtils
2026 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
2027 }
2028 }
2029
2030 private void assertNoDeviceOwnerRestrictions() {
2031 DpmTestUtils.assertRestrictions(
2032 DpmTestUtils.newRestrictions(),
2033 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2034 );
2035 DpmTestUtils.assertRestrictions(
2036 DpmTestUtils.newRestrictions(),
2037 dpm.getUserRestrictions(admin1)
2038 );
2039 }
2040
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002041 public void testGetMacAddress() throws Exception {
2042 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2043 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2044 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2045
2046 // In this test, change the caller user to "system".
2047 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2048
2049 // Make sure admin1 is installed on system user.
2050 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2051
2052 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002053 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2054 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002055
2056 // DO needs to be an DA.
2057 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2058 assertTrue(dpm.isAdminActive(admin1));
2059
2060 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002061 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2062 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002063
2064 // Test 3. Caller has PO, but not DO.
2065 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002066 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2067 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002068
2069 // Remove PO.
2070 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002071 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002072 // Test 4, Caller is DO now.
2073 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2074
xshu425b9a62018-12-13 14:18:18 -08002075 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002076 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002077
xshu425b9a62018-12-13 14:18:18 -08002078 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2079 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002080 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002081
2082 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002083 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2084 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002085 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002086 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002087
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002088 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002089 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2090 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2091
2092 // In this test, change the caller user to "system".
2093 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2094
2095 // Make sure admin1 is installed on system user.
2096 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2097
2098 // Set admin1 as DA.
2099 dpm.setActiveAdmin(admin1, false);
2100 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002101 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2102 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002103
2104 // Set admin1 as PO.
2105 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002106 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2107 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002108
2109 // Remove PO and add DO.
2110 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002111 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002112 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2113
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002114 // admin1 is DO.
2115 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002116 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002117 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002118 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2119 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002120
2121 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002122 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002123 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002124 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2125 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002126
2127 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002128 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002129 dpm.reboot(admin1);
2130 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002131
2132 public void testSetGetSupportText() {
2133 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2134 dpm.setActiveAdmin(admin1, true);
2135 dpm.setActiveAdmin(admin2, true);
2136 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2137
2138 // Null default support messages.
2139 {
2140 assertNull(dpm.getLongSupportMessage(admin1));
2141 assertNull(dpm.getShortSupportMessage(admin1));
2142 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2143 assertNull(dpm.getShortSupportMessageForUser(admin1,
2144 DpmMockContext.CALLER_USER_HANDLE));
2145 assertNull(dpm.getLongSupportMessageForUser(admin1,
2146 DpmMockContext.CALLER_USER_HANDLE));
2147 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2148 }
2149
2150 // Only system can call the per user versions.
2151 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002152 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2153 () -> dpm.getShortSupportMessageForUser(admin1,
2154 DpmMockContext.CALLER_USER_HANDLE));
2155 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2156 () -> dpm.getLongSupportMessageForUser(admin1,
2157 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002158 }
2159
2160 // Can't set message for admin in another uid.
2161 {
2162 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002163 assertExpectException(SecurityException.class,
2164 /* messageRegex= */ "is not owned by uid",
2165 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002166 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2167 }
2168
2169 // Set/Get short returns what it sets and other admins text isn't changed.
2170 {
2171 final String supportText = "Some text to test with.";
2172 dpm.setShortSupportMessage(admin1, supportText);
2173 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2174 assertNull(dpm.getLongSupportMessage(admin1));
2175 assertNull(dpm.getShortSupportMessage(admin2));
2176
2177 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2178 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2179 DpmMockContext.CALLER_USER_HANDLE));
2180 assertNull(dpm.getShortSupportMessageForUser(admin2,
2181 DpmMockContext.CALLER_USER_HANDLE));
2182 assertNull(dpm.getLongSupportMessageForUser(admin1,
2183 DpmMockContext.CALLER_USER_HANDLE));
2184 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2185
2186 dpm.setShortSupportMessage(admin1, null);
2187 assertNull(dpm.getShortSupportMessage(admin1));
2188 }
2189
2190 // Set/Get long returns what it sets and other admins text isn't changed.
2191 {
2192 final String supportText = "Some text to test with.\nWith more text.";
2193 dpm.setLongSupportMessage(admin1, supportText);
2194 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2195 assertNull(dpm.getShortSupportMessage(admin1));
2196 assertNull(dpm.getLongSupportMessage(admin2));
2197
2198 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2199 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2200 DpmMockContext.CALLER_USER_HANDLE));
2201 assertNull(dpm.getLongSupportMessageForUser(admin2,
2202 DpmMockContext.CALLER_USER_HANDLE));
2203 assertNull(dpm.getShortSupportMessageForUser(admin1,
2204 DpmMockContext.CALLER_USER_HANDLE));
2205 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2206
2207 dpm.setLongSupportMessage(admin1, null);
2208 assertNull(dpm.getLongSupportMessage(admin1));
2209 }
2210 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002211
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002212 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002213 setAsProfileOwner(admin1);
2214
2215 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002216 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002217
2218 // Setup
2219 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2220 final String package1 = "com.example.one";
2221 final String package2 = "com.example.two";
2222 pkgsToRestrict.add(package1);
2223 pkgsToRestrict.add(package2);
2224 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2225 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002226 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002227
2228 // Verify
2229 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002230 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002231 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2232 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2233 eq(DpmMockContext.CALLER_USER_HANDLE));
2234
2235 // Setup
2236 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002237 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002238
2239 // Verify
2240 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002241 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002242 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2243 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2244 eq(DpmMockContext.CALLER_USER_HANDLE));
2245 }
2246
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002247 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002248 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2249 dpm.setActiveAdmin(admin1, true);
2250 assertTrue(dpm.isAdminActive(admin1));
2251 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2252
2253 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002254 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002255 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002256 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002257 }
2258
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002259 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002260 setAsProfileOwner(admin1);
2261
2262 // Setup
2263 final ArrayList<String> emptyList = new ArrayList<>();
2264 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2265 final String package1 = "com.example.one";
2266 final String package2 = "com.example.two";
2267 final String package3 = "com.example.three";
2268 pkgsToRestrict.add(package1);
2269 pkgsToRestrict.add(package2);
2270 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2271 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002272 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002273
2274 // Verify
2275 assertEquals(emptyList, excludedPkgs);
2276 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2277 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002278 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002279 DpmMockContext.CALLER_USER_HANDLE));
2280 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002281 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002282 DpmMockContext.CALLER_USER_HANDLE));
2283 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002284 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002285 DpmMockContext.CALLER_USER_HANDLE));
2286 }
2287
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002288 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002289 setAsProfileOwner(admin1);
2290 assertExpectException(SecurityException.class,
2291 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002292 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002293 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2294 dpm.clearProfileOwner(admin1);
2295
2296 setDeviceOwner();
2297 assertExpectException(SecurityException.class,
2298 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002299 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002300 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2301 clearDeviceOwner();
2302 }
2303
phweiss73145f42017-01-17 19:06:38 +01002304 public void testCreateAdminSupportIntent() throws Exception {
2305 // Setup device owner.
2306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2307 setupDeviceOwner();
2308
2309 // Nonexisting permission returns null
2310 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2311 assertNull(intent);
2312
2313 // Existing permission that is not set returns null
2314 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2315 assertNull(intent);
2316
2317 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002318 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002319 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2320 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2321 .thenReturn(true);
2322 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2323 assertNull(intent);
2324
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002325 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2326 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2327 new UserManager.EnforcingUser(
2328 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2329 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002330 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002331 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002332 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2333 assertNotNull(intent);
2334 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2335 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2336 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002337 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002338 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2339 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2340
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002341 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2342 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002343
2344 // Camera is not disabled
2345 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2346 assertNull(intent);
2347
2348 // Camera is disabled
2349 dpm.setCameraDisabled(admin1, true);
2350 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2351 assertNotNull(intent);
2352 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2353 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2354
2355 // Screen capture is not disabled
2356 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2357 assertNull(intent);
2358
2359 // Screen capture is disabled
2360 dpm.setScreenCaptureDisabled(admin1, true);
2361 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2362 assertNotNull(intent);
2363 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2364 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2365
2366 // Same checks for different user
2367 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2368 // Camera should be disabled by device owner
2369 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2370 assertNotNull(intent);
2371 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2372 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2373 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2374 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2375 // ScreenCapture should not be disabled by device owner
2376 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2377 assertNull(intent);
2378 }
2379
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002380 /**
2381 * Test for:
2382 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002383 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002384 * {@link DevicePolicyManager#isAffiliatedUser}
2385 */
2386 public void testUserAffiliation() throws Exception {
2387 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2388 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2389 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2390
2391 // Check that the system user is unaffiliated.
2392 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2393 assertFalse(dpm.isAffiliatedUser());
2394
2395 // Set a device owner on the system user. Check that the system user becomes affiliated.
2396 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2397 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2398 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2399 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002400 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002401
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002402 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002403 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2404 setAsProfileOwner(admin2);
2405 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002406 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002407
2408 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2409 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002410 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002411 userAffiliationIds.add("red");
2412 userAffiliationIds.add("green");
2413 userAffiliationIds.add("blue");
2414 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002415 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002416 assertFalse(dpm.isAffiliatedUser());
2417
2418 // Have the device owner specify a set of affiliation ids that do not intersect with those
2419 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002420 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002421 deviceAffiliationIds.add("cyan");
2422 deviceAffiliationIds.add("yellow");
2423 deviceAffiliationIds.add("magenta");
2424 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2425 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002426 MoreAsserts.assertContentsInAnyOrder(
2427 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002428 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2429 assertFalse(dpm.isAffiliatedUser());
2430
2431 // Have the profile owner specify a set of affiliation ids that intersect with those
2432 // specified by the device owner. Check that the test user becomes affiliated.
2433 userAffiliationIds.add("yellow");
2434 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002435 MoreAsserts.assertContentsInAnyOrder(
2436 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002437 assertTrue(dpm.isAffiliatedUser());
2438
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002439 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002440 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002441 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002442 assertFalse(dpm.isAffiliatedUser());
2443
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002444 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2445 dpm.setAffiliationIds(admin2, userAffiliationIds);
2446 assertTrue(dpm.isAffiliatedUser());
2447 dpm.clearProfileOwner(admin2);
2448 assertFalse(dpm.isAffiliatedUser());
2449
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002450 // Check that the system user remains affiliated.
2451 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2452 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002453
2454 // Clear the device owner - the user becomes unaffiliated.
2455 clearDeviceOwner();
2456 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002457 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002458
2459 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002460 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002461 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2462 }
2463
2464 public void testSetUserProvisioningState_permission() throws Exception {
2465 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002466
2467 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2468 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2469 }
2470
2471 public void testSetUserProvisioningState_unprivileged() throws Exception {
2472 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002473 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2474 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2475 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002476 }
2477
2478 public void testSetUserProvisioningState_noManagement() {
2479 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002480 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002481 assertExpectException(IllegalStateException.class,
2482 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2483 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2484 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002485 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2486 }
2487
2488 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2489 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2490 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002491
2492 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2493 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2494 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2495 }
2496
2497 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2498 throws Exception {
2499 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2500 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002501
2502 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2503 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2504 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2505 }
2506
2507 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2508 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2509 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002510
2511 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2512 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2513 }
2514
2515 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2516 throws Exception {
2517 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002518
2519 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2520 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2521 DevicePolicyManager.STATE_USER_UNMANAGED);
2522 }
2523
2524 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2525 throws Exception {
2526 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002527
2528 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2529 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2530 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2531 }
2532
2533 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2534 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002535
2536 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2537 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2538 }
2539
2540 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2541 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002542
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002543 assertExpectException(IllegalStateException.class,
2544 /* messageRegex= */ "Cannot move to user provisioning state",
2545 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2546 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2547 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002548 }
2549
2550 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2551 throws Exception {
2552 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002553
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002554 assertExpectException(IllegalStateException.class,
2555 /* messageRegex= */ "Cannot move to user provisioning state",
2556 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2557 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2558 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002559 }
2560
2561 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002562 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2563 mContext.callerPermissions.add(permission.MANAGE_USERS);
2564
Alan Treadwayafad8782016-01-19 15:15:08 +00002565 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2566 for (int state : states) {
2567 dpm.setUserProvisioningState(state, userId);
2568 assertEquals(state, dpm.getUserProvisioningState());
2569 }
2570 }
2571
2572 private void setupProfileOwner() throws Exception {
2573 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2574
2575 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2576 dpm.setActiveAdmin(admin1, false);
2577 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2578
2579 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2580 }
2581
2582 private void setupDeviceOwner() throws Exception {
2583 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2584
2585 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2586 dpm.setActiveAdmin(admin1, false);
2587 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2588
2589 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2590 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002591
2592 public void testSetMaximumTimeToLock() {
2593 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2594
2595 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2596 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2597
Pavel Grafov75c0a892017-05-18 17:28:27 +01002598 reset(getServices().powerManagerInternal);
2599 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002600
2601 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002602 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2603 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002604 reset(getServices().powerManagerInternal);
2605 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002606
2607 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002608 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2609 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002610 reset(getServices().powerManagerInternal);
2611 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002612
2613 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002614 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2615 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002616 reset(getServices().powerManagerInternal);
2617 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002618
2619 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002620 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2621 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002622 reset(getServices().powerManagerInternal);
2623 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002624
2625 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002626 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2627 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002628 reset(getServices().powerManagerInternal);
2629 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002630
2631 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002632 reset(getServices().powerManagerInternal);
2633 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002634
Pavel Grafov28939982017-10-03 15:11:52 +01002635 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2636 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2637 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002638 reset(getServices().powerManagerInternal);
2639 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002640
2641 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002642 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2643 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002644 reset(getServices().powerManagerInternal);
2645 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002646
Pavel Grafov28939982017-10-03 15:11:52 +01002647 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002648 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002649 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2650 verifyStayOnWhilePluggedCleared(false);
2651 }
2652
Varun Shahb472b8f2019-09-23 23:01:06 -07002653 public void testIsActiveSupervisionApp() throws Exception {
2654 when(mServiceContext.resources
2655 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2656 .thenReturn(admin1.flattenToString());
2657
2658 final int PROFILE_USER = 15;
2659 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2660 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2661 mContext.binder.callingUid = PROFILE_ADMIN;
2662
2663 final DevicePolicyManagerInternal dpmi =
2664 LocalServices.getService(DevicePolicyManagerInternal.class);
2665 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2666 }
2667
Pavel Grafov28939982017-10-03 15:11:52 +01002668 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2669 // uses separate challenge.
2670 public void testSetMaximumTimeToLockProfile() throws Exception {
2671 final int PROFILE_USER = 15;
2672 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2673 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2674 mContext.binder.callingUid = PROFILE_ADMIN;
2675 final DevicePolicyManagerInternal dpmi =
2676 LocalServices.getService(DevicePolicyManagerInternal.class);
2677
2678 dpm.setMaximumTimeToLock(admin1, 0);
2679
2680 reset(getServices().powerManagerInternal);
2681 reset(getServices().settings);
2682
2683 // First add timeout for the profile.
2684 dpm.setMaximumTimeToLock(admin1, 10);
2685 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2686
2687 reset(getServices().powerManagerInternal);
2688 reset(getServices().settings);
2689
2690 // Add separate challenge
2691 when(getServices().lockPatternUtils
2692 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2693 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2694
2695 verifyScreenTimeoutCall(10L, PROFILE_USER);
2696 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2697
2698 reset(getServices().powerManagerInternal);
2699 reset(getServices().settings);
2700
2701 // Remove the timeout.
2702 dpm.setMaximumTimeToLock(admin1, 0);
2703 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2704 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2705
2706 reset(getServices().powerManagerInternal);
2707 reset(getServices().settings);
2708
2709 // Add it back.
2710 dpm.setMaximumTimeToLock(admin1, 10);
2711 verifyScreenTimeoutCall(10L, PROFILE_USER);
2712 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2713
2714 reset(getServices().powerManagerInternal);
2715 reset(getServices().settings);
2716
2717 // Remove separate challenge.
2718 reset(getServices().lockPatternUtils);
2719 when(getServices().lockPatternUtils
2720 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2721 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002722 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002723
2724 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2725 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2726
2727 reset(getServices().powerManagerInternal);
2728 reset(getServices().settings);
2729
2730 // Remove the timeout.
2731 dpm.setMaximumTimeToLock(admin1, 0);
2732 verifyScreenTimeoutCall(null, PROFILE_USER);
2733 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002734 }
2735
Michal Karpinski943aabd2016-10-06 11:09:25 +01002736 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2737 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2738 setupDeviceOwner();
2739 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2740
Michal Karpinskid084ca52017-01-18 15:54:18 +00002741 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2742 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2743 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2744 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2745 - ONE_MINUTE;
2746
2747 // verify that the minimum timeout cannot be modified on user builds (system property is
2748 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002749 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002750
2751 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2752 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2753 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2754
Pavel Grafov75c0a892017-05-18 17:28:27 +01002755 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002756
2757 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002758 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002759
Michal Karpinskid084ca52017-01-18 15:54:18 +00002760 // reset to default (0 means the admin is not participating, so default should be returned)
2761 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002762
2763 // aggregation should be the default if unset by any admin
2764 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2765 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2766
2767 // admin not participating by default
2768 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2769
2770 //clamping from the top
2771 dpm.setRequiredStrongAuthTimeout(admin1,
2772 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2773 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2774 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2775 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2776 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2777
Michal Karpinskid084ca52017-01-18 15:54:18 +00002778 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002779 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2780 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2781 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2782 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2783
2784 // clamping from the bottom
2785 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2786 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2787 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2788
Michal Karpinskid084ca52017-01-18 15:54:18 +00002789 // values within range
2790 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2791 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2792 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2793
2794 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2795 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2796 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002797
2798 // reset to default
2799 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2800 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2801 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2802 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2803
2804 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002805 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2806 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002807 }
2808
Pavel Grafov28939982017-10-03 15:11:52 +01002809 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002810 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002811 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002812 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002813 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002814 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002815 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002816 }
Pavel Grafov28939982017-10-03 15:11:52 +01002817 }
2818
2819 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002820 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2821 // UnfinishedVerificationException.
2822 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002823
Esteban Talavera01576862016-12-15 11:16:44 +00002824 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002825 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002826 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002827 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002828 .thenReturn(false);
2829 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002830 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2831 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002832 .thenReturn(true);
2833 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2834
2835 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002836 }
Victor Chang3e794af2016-03-04 13:48:17 +00002837
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002838 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2839 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002840 mContext.packageName = admin1.getPackageName();
2841 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2843 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2844 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2845 false);
2846 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2847 }
2848
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002849 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2850 setup_DeviceAdminFeatureOff();
2851 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2852 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2853 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2855 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2856 assertCheckProvisioningPreCondition(
2857 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2858 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2859 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2860 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2861 }
2862
Esteban Talavera01576862016-12-15 11:16:44 +00002863 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002864 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002865 .thenReturn(false);
2866 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002867 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2868 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002869 .thenReturn(true);
2870 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2871
2872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002873 }
Victor Chang3e794af2016-03-04 13:48:17 +00002874
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2876 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002877 mContext.packageName = admin1.getPackageName();
2878 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002879 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2881 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2882 false);
2883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2884
2885 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002886 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002887 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2888 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2889 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2890 true);
2891 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2892 }
2893
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2895 setup_ManagedProfileFeatureOff();
2896 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2897 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2898 DevicePolicyManager.CODE_OK);
2899 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2900 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2901 assertCheckProvisioningPreCondition(
2902 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2903 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2904 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2905 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2906
2907 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002908 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002909 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2910 DevicePolicyManager.CODE_OK);
2911 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2912 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2913 assertCheckProvisioningPreCondition(
2914 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2915 DevicePolicyManager.CODE_OK);
2916 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2917 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2918 }
2919
Esteban Talavera01576862016-12-15 11:16:44 +00002920 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002921 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002922 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002923 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2924 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002925 .thenReturn(true);
2926 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2927
2928 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002929 }
Victor Chang3e794af2016-03-04 13:48:17 +00002930
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002931 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2932 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002933 mContext.packageName = admin1.getPackageName();
2934 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002935 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2938 false /* because of non-split user */);
2939 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2940 false /* because of non-split user */);
2941 }
2942
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002943 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002944 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002945 setup_nonSplitUser_firstBoot_primaryUser();
2946 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2947 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2948 DevicePolicyManager.CODE_OK);
2949 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2950 DevicePolicyManager.CODE_OK);
2951 assertCheckProvisioningPreCondition(
2952 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2953 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2954 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2955 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2956 }
2957
Esteban Talavera01576862016-12-15 11:16:44 +00002958 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002959 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002960 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002961 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2962 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002963 .thenReturn(true);
2964 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2965
2966 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 }
Victor Chang3e794af2016-03-04 13:48:17 +00002968
Nicolas Prevot45d29072017-01-18 16:11:19 +00002969 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2970 setDeviceOwner();
2971 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2972 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2973 }
2974
2975 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2976 setup_nonSplitUser_withDo_primaryUser();
2977 final int MANAGED_PROFILE_USER_ID = 18;
2978 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2979 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002980 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002981 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002982 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002983 true)).thenReturn(true);
2984 }
2985
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002986 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2987 throws Exception {
2988 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002989 mContext.packageName = admin1.getPackageName();
2990 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002991 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2992 false/* because of completed device setup */);
2993 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2994 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2995 false/* because of non-split user */);
2996 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2997 false/* because of non-split user */);
2998 }
2999
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003000 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3001 throws Exception {
3002 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3003 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3004 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3005 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3006 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3007 DevicePolicyManager.CODE_OK);
3008 assertCheckProvisioningPreCondition(
3009 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3010 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3011 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3012 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3013 }
3014
Nicolas Prevot45d29072017-01-18 16:11:19 +00003015 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3016 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003017 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003018 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3019
3020 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3021 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003022 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003023
3024 // COMP mode is allowed.
3025 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3026 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003027 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003028
Nicolas Prevot45d29072017-01-18 16:11:19 +00003029 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003030 assertCheckProvisioningPreCondition(
3031 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003032 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003033 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003034 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3035 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3036 }
Esteban Talavera01576862016-12-15 11:16:44 +00003037
Nicolas Prevot45d29072017-01-18 16:11:19 +00003038 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3039 setup_nonSplitUser_withDo_primaryUser();
3040 mContext.packageName = admin1.getPackageName();
3041 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3042 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3043 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003044 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003045 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3046 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3047 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003048 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003049 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3050 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3051 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3052 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3053 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003055 assertCheckProvisioningPreCondition(
3056 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003057 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003058 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003059 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3060 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3061 }
Esteban Talavera01576862016-12-15 11:16:44 +00003062
Nicolas Prevot45d29072017-01-18 16:11:19 +00003063 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3064 throws Exception {
3065 setup_nonSplitUser_withDo_primaryUser();
3066 mContext.packageName = admin1.getPackageName();
3067 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003068 // The DO should not be allowed to initiate provisioning if the restriction is set by
3069 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003070 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003071 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3072 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3073 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003074 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003075 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3076 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3077 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3078 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3079 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003080 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3081
3082 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003083 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003084 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003085 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003086 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3087 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3088 }
3089
3090 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3091 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3092 mContext.packageName = admin1.getPackageName();
3093 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3094
3095 // We can delete the managed profile to create a new one, so provisioning is allowed.
3096 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3097 DevicePolicyManager.CODE_OK);
3098 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3099 assertCheckProvisioningPreCondition(
3100 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3101 DpmMockContext.ANOTHER_PACKAGE_NAME,
3102 DevicePolicyManager.CODE_OK);
3103 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3104 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3105 }
3106
3107 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3108 throws Exception {
3109 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3110 mContext.packageName = admin1.getPackageName();
3111 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003112 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003113 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3114 eq(UserHandle.SYSTEM)))
3115 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003116 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003117 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3118 eq(UserHandle.SYSTEM)))
3119 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003120
3121 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003122 assertCheckProvisioningPreCondition(
3123 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3124 DpmMockContext.ANOTHER_PACKAGE_NAME,
3125 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3126 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3127 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003128
3129 // But the device owner can still do it because it has set the restriction itself.
3130 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3131 DevicePolicyManager.CODE_OK);
3132 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003133 }
3134
3135 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003136 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003137 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003138 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3139 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003140 .thenReturn(false);
3141 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3142
3143 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003144 }
Victor Chang3e794af2016-03-04 13:48:17 +00003145
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003146 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3147 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003148 mContext.packageName = admin1.getPackageName();
3149 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003150 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3151 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3152 false /* because canAddMoreManagedProfiles returns false */);
3153 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3154 true);
3155 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3156 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003157 }
3158
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003159 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3160 throws Exception {
3161 setup_splitUser_firstBoot_systemUser();
3162 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3163 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3164 DevicePolicyManager.CODE_OK);
3165 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003166 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003167 assertCheckProvisioningPreCondition(
3168 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3169 DevicePolicyManager.CODE_OK);
3170 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3171 DevicePolicyManager.CODE_SYSTEM_USER);
3172 }
3173
Esteban Talavera01576862016-12-15 11:16:44 +00003174 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003175 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003176 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003177 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3178 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003179 .thenReturn(false);
3180 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3181
3182 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003183 }
Victor Chang3e794af2016-03-04 13:48:17 +00003184
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003185 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3186 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003187 mContext.packageName = admin1.getPackageName();
3188 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003189 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3190 true/* it's undefined behavior. Can be changed into false in the future */);
3191 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3192 false /* because canAddMoreManagedProfiles returns false */);
3193 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3194 true/* it's undefined behavior. Can be changed into false in the future */);
3195 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3196 false/* because calling uid is system user */);
3197 }
3198
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003199 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3200 throws Exception {
3201 setup_splitUser_afterDeviceSetup_systemUser();
3202 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3203 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3204 DevicePolicyManager.CODE_OK);
3205 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003206 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003207 assertCheckProvisioningPreCondition(
3208 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3209 DevicePolicyManager.CODE_OK);
3210 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3211 DevicePolicyManager.CODE_SYSTEM_USER);
3212 }
3213
Esteban Talavera01576862016-12-15 11:16:44 +00003214 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003215 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003216 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003217 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3218 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003219 true)).thenReturn(true);
3220 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3221
3222 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003223 }
Victor Chang3e794af2016-03-04 13:48:17 +00003224
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003225 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3226 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003227 mContext.packageName = admin1.getPackageName();
3228 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003229 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3230 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3231 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3232 true);
3233 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003234 }
3235
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003237 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003238 setup_splitUser_firstBoot_primaryUser();
3239 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3240 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3241 DevicePolicyManager.CODE_OK);
3242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3243 DevicePolicyManager.CODE_OK);
3244 assertCheckProvisioningPreCondition(
3245 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3246 DevicePolicyManager.CODE_OK);
3247 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3248 DevicePolicyManager.CODE_OK);
3249 }
3250
Esteban Talavera01576862016-12-15 11:16:44 +00003251 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003252 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003253 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003254 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3255 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003256 true)).thenReturn(true);
3257 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3258
3259 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003260 }
Victor Chang3e794af2016-03-04 13:48:17 +00003261
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003262 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3263 throws Exception {
3264 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003265 mContext.packageName = admin1.getPackageName();
3266 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003267 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3268 true/* it's undefined behavior. Can be changed into false in the future */);
3269 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3270 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3271 true/* it's undefined behavior. Can be changed into false in the future */);
3272 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3273 false/* because user setup completed */);
3274 }
3275
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003276 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003277 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003278 setup_splitUser_afterDeviceSetup_primaryUser();
3279 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3280 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3281 DevicePolicyManager.CODE_OK);
3282 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3283 DevicePolicyManager.CODE_OK);
3284 assertCheckProvisioningPreCondition(
3285 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3286 DevicePolicyManager.CODE_OK);
3287 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3288 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3289 }
3290
Esteban Talavera01576862016-12-15 11:16:44 +00003291 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003292 setDeviceOwner();
3293
Pavel Grafov75c0a892017-05-18 17:28:27 +01003294 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003295 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003296 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3297 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003298 .thenReturn(false);
3299 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3300
3301 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003302 }
Victor Chang3e794af2016-03-04 13:48:17 +00003303
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003304 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3305 throws Exception {
3306 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003307 mContext.packageName = admin1.getPackageName();
3308 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003309 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3310 false /* can't provision managed profile on system user */);
3311 }
3312
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003313 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003314 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003315 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3316 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3317 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3318 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3319 }
3320
3321 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003322 setDeviceOwner();
3323
Pavel Grafov75c0a892017-05-18 17:28:27 +01003324 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003325 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003326 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3327 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003328 true)).thenReturn(true);
3329 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3330
3331 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003332 }
Victor Chang3e794af2016-03-04 13:48:17 +00003333
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003334 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3335 throws Exception {
3336 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003337 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3338 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003339 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3340 }
3341
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003342 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003343 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003344 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3345 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003346
3347 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003348 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3349 DevicePolicyManager.CODE_OK);
3350 }
3351
3352 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003353 setDeviceOwner();
3354
Pavel Grafov75c0a892017-05-18 17:28:27 +01003355 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003356 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003357 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3358 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003359 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3360 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003361 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003362 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003363 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003364 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003365 true)).thenReturn(true);
3366 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3367
3368 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003369 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003370
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003371 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3372 throws Exception {
3373 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003374 mContext.packageName = admin1.getPackageName();
3375 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003376 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3377 }
3378
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003379 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3380 throws Exception {
3381 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3382 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3383 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3384 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3385 }
3386
3387 public void testCheckProvisioningPreCondition_permission() {
3388 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003389 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3390 () -> dpm.checkProvisioningPreCondition(
3391 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003392 }
3393
Victor Chang3577ed22016-08-25 18:49:26 +01003394 public void testForceUpdateUserSetupComplete_permission() {
3395 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003396 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3397 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003398 }
3399
3400 public void testForceUpdateUserSetupComplete_systemUser() {
3401 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3402 // GIVEN calling from user 20
3403 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003404 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3405 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003406 }
3407
3408 public void testForceUpdateUserSetupComplete_userbuild() {
3409 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3410 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3411
3412 final int userId = UserHandle.USER_SYSTEM;
3413 // GIVEN userComplete is false in SettingsProvider
3414 setUserSetupCompleteForUser(false, userId);
3415
3416 // GIVEN userComplete is true in DPM
3417 DevicePolicyManagerService.DevicePolicyData userData =
3418 new DevicePolicyManagerService.DevicePolicyData(userId);
3419 userData.mUserSetupComplete = true;
3420 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3421
3422 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003423 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003424
3425 assertTrue(dpms.hasUserSetupCompleted());
3426
3427 dpm.forceUpdateUserSetupComplete();
3428
3429 // THEN the state in dpms is not changed
3430 assertTrue(dpms.hasUserSetupCompleted());
3431 }
3432
3433 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3434 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3435 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3436
3437 final int userId = UserHandle.USER_SYSTEM;
3438 // GIVEN userComplete is false in SettingsProvider
3439 setUserSetupCompleteForUser(false, userId);
3440
3441 // GIVEN userComplete is true in DPM
3442 DevicePolicyManagerService.DevicePolicyData userData =
3443 new DevicePolicyManagerService.DevicePolicyData(userId);
3444 userData.mUserSetupComplete = true;
3445 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3446
3447 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003448 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003449
3450 assertTrue(dpms.hasUserSetupCompleted());
3451
3452 dpm.forceUpdateUserSetupComplete();
3453
3454 // THEN the state in dpms is not changed
3455 assertFalse(dpms.hasUserSetupCompleted());
3456 }
3457
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003458 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003459 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003460 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003461
3462 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3463 runAsCaller(mAdmin1Context, dpms, dpm -> {
3464 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3465 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003466 }
3467
3468 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3469 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3470 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003471
3472 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3473 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003474 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003475 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3476 .thenReturn(true);
3477
3478 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003479 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003480
3481 // Enabling logging should not change the timestamp.
3482 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003483 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003484 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003485 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003486 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003487 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003488
3489 // Retrieving the logs should update the timestamp.
3490 final long beforeRetrieval = System.currentTimeMillis();
3491 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003492 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003493 final long afterRetrieval = System.currentTimeMillis();
3494 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3495 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3496
3497 // Retrieving the pre-boot logs should update the timestamp.
3498 Thread.sleep(2);
3499 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003500 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003501 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3502
3503 // Checking the timestamp again should not change it.
3504 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003505 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003506
3507 // Retrieving the logs again should update the timestamp.
3508 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003509 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003510 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3511
3512 // Disabling logging should not change the timestamp.
3513 Thread.sleep(2);
3514 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003515 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003516
3517 // Restarting the DPMS should not lose the timestamp.
3518 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003519 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003520
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003521 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3522 mContext.binder.callingUid = 1234567;
3523 mContext.callerPermissions.add(permission.MANAGE_USERS);
3524 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3525 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3526
3527 // System can retrieve the timestamp.
3528 mContext.binder.clearCallingIdentity();
3529 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3530
3531 // Removing the device owner should clear the timestamp.
3532 clearDeviceOwner();
3533 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003534 }
3535
yuemingw0de748d2017-11-15 19:22:27 +00003536 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3537 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3538 setupDeviceOwner();
3539 assertExpectException(SecurityException.class, null, () ->
3540 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3541 }
3542
yuemingwc0281f12018-03-28 15:58:49 +01003543 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003544 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3545 setupDeviceOwner();
3546 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003547 verify(getServices().settings).settingsSystemPutStringForUser(
3548 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3549 }
3550
3551 public void testSetSystemSettingWithPO() throws Exception {
3552 setupProfileOwner();
3553 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3554 verify(getServices().settings).settingsSystemPutStringForUser(
3555 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003556 }
3557
yuemingwe43cdf72017-10-12 16:52:11 +01003558 public void testSetTime() throws Exception {
3559 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3560 setupDeviceOwner();
3561 dpm.setTime(admin1, 0);
3562 verify(getServices().alarmManager).setTime(0);
3563 }
3564
3565 public void testSetTimeFailWithPO() throws Exception {
3566 setupProfileOwner();
3567 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3568 }
3569
3570 public void testSetTimeWithAutoTimeOn() throws Exception {
3571 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3572 setupDeviceOwner();
3573 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3574 .thenReturn(1);
3575 assertFalse(dpm.setTime(admin1, 0));
3576 }
3577
3578 public void testSetTimeZone() throws Exception {
3579 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3580 setupDeviceOwner();
3581 dpm.setTimeZone(admin1, "Asia/Shanghai");
3582 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3583 }
3584
3585 public void testSetTimeZoneFailWithPO() throws Exception {
3586 setupProfileOwner();
3587 assertExpectException(SecurityException.class, null,
3588 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3589 }
3590
3591 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3592 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3593 setupDeviceOwner();
3594 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3595 .thenReturn(1);
3596 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3597 }
3598
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003599 public void testGetLastBugReportRequestTime() throws Exception {
3600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3601 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003602
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003603 mContext.packageName = admin1.getPackageName();
3604 mContext.applicationInfo = new ApplicationInfo();
3605 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3606 .thenReturn(Color.WHITE);
3607 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3608 anyObject())).thenReturn(Color.WHITE);
3609
Esteban Talaverad36dd152016-12-15 08:51:45 +00003610 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3611 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003612 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003613
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003614 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003615 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003616
3617 // Requesting a bug report should update the timestamp.
3618 final long beforeRequest = System.currentTimeMillis();
3619 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003620 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003621 final long afterRequest = System.currentTimeMillis();
3622 assertTrue(bugReportRequestTime >= beforeRequest);
3623 assertTrue(bugReportRequestTime <= afterRequest);
3624
3625 // Checking the timestamp again should not change it.
3626 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003627 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003628
3629 // Restarting the DPMS should not lose the timestamp.
3630 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003631 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003632
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003633 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3634 mContext.binder.callingUid = 1234567;
3635 mContext.callerPermissions.add(permission.MANAGE_USERS);
3636 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3637 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3638
3639 // System can retrieve the timestamp.
3640 mContext.binder.clearCallingIdentity();
3641 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3642
3643 // Removing the device owner should clear the timestamp.
3644 clearDeviceOwner();
3645 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003646 }
3647
3648 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3649 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3650 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003651 mContext.packageName = admin1.getPackageName();
3652 mContext.applicationInfo = new ApplicationInfo();
3653 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3654 .thenReturn(Color.WHITE);
3655 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3656 anyObject())).thenReturn(Color.WHITE);
3657
3658 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3659 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003660 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003661 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003662 .thenReturn(true);
3663
3664 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003665 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003666
3667 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3668 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003669 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003670
3671 // Enabling logging should not change the timestamp.
3672 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003673 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003674
3675 // Retrieving the logs should update the timestamp.
3676 final long beforeRetrieval = System.currentTimeMillis();
3677 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003678 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003679 final long afterRetrieval = System.currentTimeMillis();
3680 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3681 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3682
3683 // Checking the timestamp again should not change it.
3684 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003685 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003686
3687 // Retrieving the logs again should update the timestamp.
3688 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003689 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003690 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3691
3692 // Disabling logging should not change the timestamp.
3693 Thread.sleep(2);
3694 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003695 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003696
3697 // Restarting the DPMS should not lose the timestamp.
3698 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003699 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3700
3701 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3702 mContext.binder.callingUid = 1234567;
3703 mContext.callerPermissions.add(permission.MANAGE_USERS);
3704 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3705 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3706
3707 // System can retrieve the timestamp.
3708 mContext.binder.clearCallingIdentity();
3709 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3710
3711 // Removing the device owner should clear the timestamp.
3712 clearDeviceOwner();
3713 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003714 }
3715
Tony Mak2f26b792016-11-28 17:54:51 +00003716 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3717 // Setup device owner.
3718 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3719 setupDeviceOwner();
3720
3721 // Only device owner is setup, the result list should be empty.
3722 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3723 MoreAsserts.assertEmpty(targetUsers);
3724
3725 // Setup a managed profile managed by the same admin.
3726 final int MANAGED_PROFILE_USER_ID = 15;
3727 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3728 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3729
3730 // Add a secondary user, it should never talk with.
3731 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003732 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003733
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003734 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3735 // other.
3736 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3737 MoreAsserts.assertEmpty(targetUsers);
3738
3739 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3740 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3741 MoreAsserts.assertEmpty(targetUsers);
3742
3743 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003744 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003745 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3746 dpm.setAffiliationIds(admin1, userAffiliationIds);
3747
3748 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3749 dpm.setAffiliationIds(admin1, userAffiliationIds);
3750
Tony Mak2f26b792016-11-28 17:54:51 +00003751 // Calling from device owner admin, the result list should just contain the managed
3752 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003753 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003754 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3755 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3756
3757 // Calling from managed profile admin, the result list should just contain the system
3758 // user id.
3759 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3760 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3761 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003762
3763 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003764 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003765
3766 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3767 // to each other.
3768 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3769 MoreAsserts.assertEmpty(targetUsers);
3770
3771 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3772 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3773 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003774 }
3775
3776 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3777 // Setup a device owner.
3778 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3779 setupDeviceOwner();
3780
3781 // Set up a managed profile managed by different package.
3782 final int MANAGED_PROFILE_USER_ID = 15;
3783 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3784 final ComponentName adminDifferentPackage =
3785 new ComponentName("another.package", "whatever.class");
3786 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3787
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003788 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003789 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003790 dpm.setAffiliationIds(admin1, userAffiliationIds);
3791
3792 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3793 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3794
Tony Mak2f26b792016-11-28 17:54:51 +00003795 // Calling from device owner admin, we should get zero bind device admin target users as
3796 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003797 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003798 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3799 MoreAsserts.assertEmpty(targetUsers);
3800
3801 // Calling from managed profile admin, we should still get zero target users for the same
3802 // reason.
3803 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3804 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3805 MoreAsserts.assertEmpty(targetUsers);
3806 }
3807
Jason Parks3c13b642017-11-28 15:39:43 -06003808 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003809 verifyLockTaskState(userId, new String[0],
3810 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003811 }
3812
3813 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3814 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003815 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003816 }
3817
3818 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3819 int flags) throws Exception {
3820 mContext.binder.callingUid = uid;
3821 dpm.setLockTaskPackages(who, packages);
3822 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3823 for (String p : packages) {
3824 assertTrue(dpm.isLockTaskPermitted(p));
3825 }
3826 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3827 // Test to see if set lock task features can be set
3828 dpm.setLockTaskFeatures(who, flags);
3829 verifyLockTaskState(userId, packages, flags);
3830 }
3831
3832 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3833 int flags) throws Exception {
3834 mContext.binder.callingUid = uid;
3835 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3836 () -> dpm.setLockTaskPackages(who, packages));
3837 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3838 () -> dpm.getLockTaskPackages(who));
3839 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3840 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3841 () -> dpm.setLockTaskFeatures(who, flags));
3842 }
3843
Charles Hee078db72017-10-19 18:03:20 +01003844 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003845 // Setup a device owner.
3846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3847 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003848 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003849 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003850
3851 // Set up a managed profile managed by different package (package name shouldn't matter)
3852 final int MANAGED_PROFILE_USER_ID = 15;
3853 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3854 final ComponentName adminDifferentPackage =
3855 new ComponentName("another.package", "whatever.class");
3856 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003857 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3858
3859 // Setup a PO on the secondary user
3860 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3861 setAsProfileOwner(admin3);
3862 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003863
3864 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003865 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003866 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003867 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3868 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003869 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3870
3871 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3872 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003873 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3874 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003875 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003876
3877 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3878 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3879 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003880 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003881 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3882 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003883 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003884
3885 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003886 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003887 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3888 dpm.setAffiliationIds(admin1, userAffiliationIds);
3889
3890 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3891 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3892
3893 // Now the managed profile can set lock task packages.
3894 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3895 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3896 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3897 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003898 // And it can set lock task features.
3899 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003900 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003901
3902 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003903 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003904 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3905 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003906 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3907 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003908 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003909 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003910
Jason Parks3c13b642017-11-28 15:39:43 -06003911 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003912 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3913 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003914
3915 }
3916
3917 public void testLockTaskPolicyForProfileOwner() throws Exception {
3918 // Setup a PO
3919 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3920 setAsProfileOwner(admin1);
3921 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3922
3923 final String[] poPackages = {"poPackage1", "poPackage2"};
3924 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003925 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3926 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003927 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3928 poPackages, poFlags);
3929
3930 // Set up a managed profile managed by different package (package name shouldn't matter)
3931 final int MANAGED_PROFILE_USER_ID = 15;
3932 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3933 final ComponentName adminDifferentPackage =
3934 new ComponentName("another.package", "whatever.class");
3935 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3936 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3937
3938 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3939 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3940 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3941 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003942 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3943 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003944 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003945 }
3946
Benjamin Franzcaffa772018-02-05 16:36:10 +00003947 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3948 // Setup a device owner.
3949 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3950 setupDeviceOwner();
3951 // Lock task policy is updated when loading user data.
3952 verifyLockTaskState(UserHandle.USER_SYSTEM);
3953
3954 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3955 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3956 assertExpectException(IllegalArgumentException.class,
3957 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3958 () -> dpm.setLockTaskFeatures(admin1, flags));
3959 }
3960
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003961 public void testIsDeviceManaged() throws Exception {
3962 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3963 setupDeviceOwner();
3964
3965 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3966 // find out that the device has a device owner.
3967 assertTrue(dpm.isDeviceManaged());
3968 mContext.binder.callingUid = 1234567;
3969 mContext.callerPermissions.add(permission.MANAGE_USERS);
3970 assertTrue(dpm.isDeviceManaged());
3971 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3972 mContext.binder.clearCallingIdentity();
3973 assertTrue(dpm.isDeviceManaged());
3974
3975 clearDeviceOwner();
3976
3977 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3978 // not have a device owner.
3979 mContext.binder.callingUid = 1234567;
3980 mContext.callerPermissions.add(permission.MANAGE_USERS);
3981 assertFalse(dpm.isDeviceManaged());
3982 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3983 mContext.binder.clearCallingIdentity();
3984 assertFalse(dpm.isDeviceManaged());
3985 }
3986
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003987 public void testDeviceOwnerOrganizationName() throws Exception {
3988 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3989 setupDeviceOwner();
3990
3991 dpm.setOrganizationName(admin1, "organization");
3992
3993 // Device owner can retrieve organization managing the device.
3994 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3995
3996 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3997 mContext.binder.callingUid = 1234567;
3998 mContext.callerPermissions.add(permission.MANAGE_USERS);
3999 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4000 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4001
4002 // System can retrieve organization managing the device.
4003 mContext.binder.clearCallingIdentity();
4004 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4005
4006 // Removing the device owner clears the organization managing the device.
4007 clearDeviceOwner();
4008 assertNull(dpm.getDeviceOwnerOrganizationName());
4009 }
4010
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004011 public void testWipeDataManagedProfile() throws Exception {
4012 final int MANAGED_PROFILE_USER_ID = 15;
4013 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4014 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4015 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4016
4017 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004018 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004019 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004020 // Get mock reason string since we throw an IAE with empty string input.
4021 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4022 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004023
4024 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004025 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004026 MANAGED_PROFILE_USER_ID);
4027 }
4028
4029 public void testWipeDataManagedProfileDisallowed() throws Exception {
4030 final int MANAGED_PROFILE_USER_ID = 15;
4031 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4032 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4033
4034 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004035 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004036 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4037
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004039 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4040 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4041 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004042 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4043 thenReturn("Just a test string.");
4044
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004045 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004046 // The PO is not allowed to remove the profile if the user restriction was set on the
4047 // profile by the system
4048 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4049 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004050 }
4051
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004052 public void testWipeDataDeviceOwner() throws Exception {
4053 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004054 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004055 UserManager.DISALLOW_FACTORY_RESET,
4056 UserHandle.SYSTEM))
4057 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004058 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4059 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004060
4061 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004062 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004063 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4064 /*wipeEuicc=*/ eq(false));
4065 }
4066
4067 public void testWipeEuiccDataEnabled() throws Exception {
4068 setDeviceOwner();
4069 when(getServices().userManager.getUserRestrictionSource(
4070 UserManager.DISALLOW_FACTORY_RESET,
4071 UserHandle.SYSTEM))
4072 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004073 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4074 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004075
4076 dpm.wipeData(WIPE_EUICC);
4077 verify(getServices().recoverySystem).rebootWipeUserData(
4078 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4079 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004080 }
4081
4082 public void testWipeDataDeviceOwnerDisallowed() 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);
yuemingwf7f67dc2017-09-08 14:23:53 +01004088 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4089 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004090 // The DO is not allowed to wipe the device if the user restriction was set
4091 // by the system
4092 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4093 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004094 }
4095
4096 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4097 final int MANAGED_PROFILE_USER_ID = 15;
4098 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4099 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4100
4101 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004102 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004103 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4104
Pavel Grafov75c0a892017-05-18 17:28:27 +01004105 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004106 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4107 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4108 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4109
4110 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4111 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4112
4113 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4114 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4115 // Failed password attempts on the parent user are taken into account, as there isn't a
4116 // separate work challenge.
4117 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4118 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4119 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4120
4121 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4122 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004124 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004125 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004126 }
4127
4128 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4129 throws Exception {
4130 final int MANAGED_PROFILE_USER_ID = 15;
4131 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4132 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4133
4134 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004135 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004136 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4137
Pavel Grafov75c0a892017-05-18 17:28:27 +01004138 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004139 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4140 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4141 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4142
4143 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4144 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4145
4146 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4147 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4148 // Failed password attempts on the parent user are taken into account, as there isn't a
4149 // separate work challenge.
4150 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4151 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4152 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4153
4154 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4155 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004156 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004157 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004158 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004159 }
4160
4161 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4162 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004164 UserManager.DISALLOW_FACTORY_RESET,
4165 UserHandle.SYSTEM))
4166 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4167
4168 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4169
4170 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4171 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4172 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4173 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4174 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4175
4176 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4177 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004178 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004179 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4180 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004181 }
4182
4183 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4184 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004185 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004186 UserManager.DISALLOW_FACTORY_RESET,
4187 UserHandle.SYSTEM))
4188 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4189
4190 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4191
4192 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4193 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4194 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4195 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4196 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4197
4198 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004199 verifyZeroInteractions(getServices().recoverySystem);
4200 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004201 .removeUserEvenWhenDisallowed(anyInt());
4202 }
4203
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004204 public void testGetPermissionGrantState() throws Exception {
4205 final String permission = "some.permission";
4206 final String app1 = "com.example.app1";
4207 final String app2 = "com.example.app2";
4208
Pavel Grafov75c0a892017-05-18 17:28:27 +01004209 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004210 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004211 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004212 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004213 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004214 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4215 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004216 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004217 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004218 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004219 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004220 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004221 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4222
4223 // System can retrieve permission grant state.
4224 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004225 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004226 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4227 dpm.getPermissionGrantState(null, app1, permission));
4228 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4229 dpm.getPermissionGrantState(null, app2, permission));
4230
4231 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004232 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4233 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004234 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4235 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004236
4237 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004238 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4239 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004240 setAsProfileOwner(admin1);
4241 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4242 dpm.getPermissionGrantState(admin1, app1, permission));
4243 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4244 dpm.getPermissionGrantState(admin1, app2, permission));
4245 }
4246
Rubin Xuaab7a412016-12-30 21:13:29 +00004247 public void testResetPasswordWithToken() throws Exception {
4248 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4249 setupDeviceOwner();
4250 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004251 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4252 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4253
Rubin Xuaab7a412016-12-30 21:13:29 +00004254 // test adding a token
4255 final byte[] token = new byte[32];
4256 final long handle = 123456;
4257 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004258 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4259 nullable(EscrowTokenStateChangeCallback.class)))
4260 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004261 assertTrue(dpm.setResetPasswordToken(admin1, token));
4262
4263 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004264 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004265 .thenReturn(true);
4266 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4267
4268 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004269 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004270 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004271 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004272 eq(UserHandle.USER_SYSTEM)))
4273 .thenReturn(true);
4274 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4275
4276 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004278 .thenReturn(true);
4279 assertTrue(dpm.clearResetPasswordToken(admin1));
4280 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004281
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004282 public void testIsActivePasswordSufficient() throws Exception {
4283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4284 mContext.packageName = admin1.getPackageName();
4285 setupDeviceOwner();
4286
4287 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4288 dpm.setPasswordMinimumLength(admin1, 8);
4289 dpm.setPasswordMinimumLetters(admin1, 6);
4290 dpm.setPasswordMinimumLowerCase(admin1, 3);
4291 dpm.setPasswordMinimumUpperCase(admin1, 1);
4292 dpm.setPasswordMinimumNonLetter(admin1, 1);
4293 dpm.setPasswordMinimumNumeric(admin1, 1);
4294 dpm.setPasswordMinimumSymbols(admin1, 0);
4295
Rubin Xucc391c22018-01-02 20:37:35 +00004296 reset(mContext.spiedContext);
4297
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004298 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4299 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4300 8, 2,
4301 6, 1,
4302 0, 1);
4303
4304 setActivePasswordState(passwordMetricsNoSymbols);
4305 assertTrue(dpm.isActivePasswordSufficient());
4306
4307 initializeDpms();
4308 reset(mContext.spiedContext);
4309 assertTrue(dpm.isActivePasswordSufficient());
4310
4311 // This call simulates the user entering the password for the first time after a reboot.
4312 // This causes password metrics to be reloaded into memory. Until this happens,
4313 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4314 // even if the DPC changes password requirements so that the password no longer meets the
4315 // requirements. This is a known limitation of the current implementation of
4316 // isActivePasswordSufficient() - see b/34218769.
4317 setActivePasswordState(passwordMetricsNoSymbols);
4318 assertTrue(dpm.isActivePasswordSufficient());
4319
4320 dpm.setPasswordMinimumSymbols(admin1, 1);
4321 // This assertion would fail if we had not called setActivePasswordState() again after
4322 // initializeDpms() - see previous comment.
4323 assertFalse(dpm.isActivePasswordSufficient());
4324
4325 initializeDpms();
4326 reset(mContext.spiedContext);
4327 assertFalse(dpm.isActivePasswordSufficient());
4328
4329 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4330 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4331 7, 2,
4332 5, 1,
4333 1, 2);
4334
4335 setActivePasswordState(passwordMetricsWithSymbols);
4336 assertTrue(dpm.isActivePasswordSufficient());
4337 }
4338
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004339 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4340 // If there is no lock screen, the password is considered empty no matter what, because
4341 // it provides no security.
4342 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4343
4344 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4345 mContext.packageName = admin1.getPackageName();
4346 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004347 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4348 // When there is no lockscreen, user password metrics is always empty.
4349 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4350 .thenReturn(new PasswordMetrics());
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004351
4352 // If no password requirements are set, isActivePasswordSufficient should succeed.
4353 assertTrue(dpm.isActivePasswordSufficient());
4354
4355 // Now set some password quality requirements.
4356 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4357
4358 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004359 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004360 dpm.reportPasswordChanged(userHandle);
4361
4362 // No broadcast should be sent.
4363 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4364 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4365 MockUtils.checkUserHandle(userHandle));
4366
4367 // The active (nonexistent) password doesn't comply with the requirements.
4368 assertFalse(dpm.isActivePasswordSufficient());
4369 }
4370
Pavel Grafov75c0a892017-05-18 17:28:27 +01004371 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4372 throws Exception {
4373 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004374 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004375
Rubin Xu19854862019-08-15 16:37:23 +01004376 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4377 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004378 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004379
Rubin Xucc391c22018-01-02 20:37:35 +00004380 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4381 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004382 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004383 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4384 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004385 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004386 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4387 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004388 // userId, if the password checkpoint value changes.
4389 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4390 MockUtils.checkIntentAction(
4391 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4392 MockUtils.checkUserHandle(userHandle));
4393 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004394 MockUtils.checkIntentAction(
4395 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4396 MockUtils.checkUserHandle(userHandle));
4397
Pavel Grafov75c0a892017-05-18 17:28:27 +01004398 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4399 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004400 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004401
4402 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4403 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004404 MockUtils.checkUserHandle(userHandle),
4405 eq(null),
4406 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004407
4408 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4409 // let it finish with system uid, otherwise it will throw and crash.
4410 flushTasks();
4411
4412 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004413 }
4414
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004415 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4416 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4417 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4418 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4419 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4420 DpmMockContext.SYSTEM_UID);
4421 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4422 DpmMockContext.SYSTEM_UID);
4423
4424 // Set up a device owner.
4425 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004426 setupDeviceOwner();
4427
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 // First and second user set IMEs manually.
4429 mContext.binder.callingUid = firstUserSystemUid;
4430 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4431 mContext.binder.callingUid = secondUserSystemUid;
4432 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004433
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004434 // Device owner changes IME for first user.
4435 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004436 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004437 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004438 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004439 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004440 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004441 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004442 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4443 mContext.binder.callingUid = firstUserSystemUid;
4444 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4445 mContext.binder.callingUid = secondUserSystemUid;
4446 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004447
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004448 // Second user changes IME manually.
4449 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4450 mContext.binder.callingUid = firstUserSystemUid;
4451 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4452 mContext.binder.callingUid = secondUserSystemUid;
4453 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004454
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004455 // First user changes IME manually.
4456 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4457 mContext.binder.callingUid = firstUserSystemUid;
4458 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4459 mContext.binder.callingUid = secondUserSystemUid;
4460 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004461
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004462 // Device owner changes IME for first user again.
4463 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004464 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004465 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004466 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004467 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004468 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004469 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4470 mContext.binder.callingUid = firstUserSystemUid;
4471 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4472 mContext.binder.callingUid = secondUserSystemUid;
4473 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004474
4475 // Restarting the DPMS should not lose information.
4476 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004477 mContext.binder.callingUid = firstUserSystemUid;
4478 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4479 mContext.binder.callingUid = secondUserSystemUid;
4480 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004481
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004482 // Device owner can find out whether it set the current IME itself.
4483 mContext.binder.callingUid = deviceOwnerUid;
4484 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004485
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004486 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004487 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004488 mContext.binder.callingUid = firstUserSystemUid;
4489 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4490 mContext.binder.callingUid = secondUserSystemUid;
4491 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004492 }
4493
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004494 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4495 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4496 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4497 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4498 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4499 DpmMockContext.SYSTEM_UID);
4500 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4501 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004502
4503 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004504 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004505 setupProfileOwner();
4506
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004507 // First and second user set IMEs manually.
4508 mContext.binder.callingUid = firstUserSystemUid;
4509 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4510 mContext.binder.callingUid = secondUserSystemUid;
4511 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004512
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004513 // Profile owner changes IME for second user.
4514 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004515 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004516 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004517 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004518 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004519 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004520 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004521 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4522 mContext.binder.callingUid = firstUserSystemUid;
4523 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4524 mContext.binder.callingUid = secondUserSystemUid;
4525 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004526
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004527 // First user changes IME manually.
4528 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4529 mContext.binder.callingUid = firstUserSystemUid;
4530 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4531 mContext.binder.callingUid = secondUserSystemUid;
4532 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004533
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004534 // Second user changes IME manually.
4535 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4536 mContext.binder.callingUid = firstUserSystemUid;
4537 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4538 mContext.binder.callingUid = secondUserSystemUid;
4539 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004540
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004541 // Profile owner changes IME for second user again.
4542 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004543 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004544 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004545 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004546 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004547 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004548 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4549 mContext.binder.callingUid = firstUserSystemUid;
4550 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4551 mContext.binder.callingUid = secondUserSystemUid;
4552 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004553
4554 // Restarting the DPMS should not lose information.
4555 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004556 mContext.binder.callingUid = firstUserSystemUid;
4557 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4558 mContext.binder.callingUid = secondUserSystemUid;
4559 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004560
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004561 // Profile owner can find out whether it set the current IME itself.
4562 mContext.binder.callingUid = profileOwnerUid;
4563 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004564
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004565 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004566 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004567 mContext.binder.callingUid = firstUserSystemUid;
4568 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4569 mContext.binder.callingUid = secondUserSystemUid;
4570 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004571 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004572
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004573 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4574 throws Exception {
4575 // Set up a device owner.
4576 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4577 setupDeviceOwner();
4578 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4579 }
4580
4581 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4582 throws Exception {
4583 // Set up a profile owner.
4584 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4585 setupProfileOwner();
4586 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4587 }
4588
4589 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4590 int adminUid) throws Exception {
4591 mContext.binder.callingUid = adminUid;
4592 final int userId = UserHandle.getUserId(adminUid);
4593
4594 final String packageName = "some.package";
4595 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4596 admin1, Collections.singletonList(packageName)));
4597 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4598
4599 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4600 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4601
4602 // Attempt to set to empty list (which means no listener is whitelisted)
4603 mContext.binder.callingUid = adminUid;
4604 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004605 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004606 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4607
4608 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4609 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4610 }
4611
4612 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4613 // Set up a managed profile
4614 final int MANAGED_PROFILE_USER_ID = 15;
4615 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4616 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4617 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4618
4619 final String permittedListener = "some.package";
4620 setupPackageInPackageManager(
4621 permittedListener,
4622 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4623 /*appId=*/ 12345, /*flags=*/ 0);
4624
4625 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4626 admin1, Collections.singletonList(permittedListener)));
4627
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004628 // isNotificationListenerServicePermitted should throw if not called from System.
4629 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4630 () -> dpms.isNotificationListenerServicePermitted(
4631 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004632
4633 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4634 assertTrue(dpms.isNotificationListenerServicePermitted(
4635 permittedListener, MANAGED_PROFILE_USER_ID));
4636 }
4637
4638 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4639 throws Exception {
4640 // Set up a managed profile
4641 final int MANAGED_PROFILE_USER_ID = 15;
4642 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4643 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4644 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4645
4646 final String permittedListener = "permitted.package";
4647 int appId = 12345;
4648 setupPackageInPackageManager(
4649 permittedListener,
4650 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4651 appId, /*flags=*/ 0);
4652
4653 final String notPermittedListener = "not.permitted.package";
4654 setupPackageInPackageManager(
4655 notPermittedListener,
4656 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4657 ++appId, /*flags=*/ 0);
4658
4659 final String systemListener = "system.package";
4660 setupPackageInPackageManager(
4661 systemListener,
4662 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4663 ++appId, ApplicationInfo.FLAG_SYSTEM);
4664
4665 // By default all packages are allowed
4666 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4667
4668 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4669 assertTrue(dpms.isNotificationListenerServicePermitted(
4670 permittedListener, MANAGED_PROFILE_USER_ID));
4671 assertTrue(dpms.isNotificationListenerServicePermitted(
4672 notPermittedListener, MANAGED_PROFILE_USER_ID));
4673 assertTrue(dpms.isNotificationListenerServicePermitted(
4674 systemListener, MANAGED_PROFILE_USER_ID));
4675
4676 // Setting only one package in the whitelist
4677 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4678 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4679 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004680 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004681 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4682 assertEquals(1, permittedListeners.size());
4683 assertEquals(permittedListener, permittedListeners.get(0));
4684
4685 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4686 assertTrue(dpms.isNotificationListenerServicePermitted(
4687 permittedListener, MANAGED_PROFILE_USER_ID));
4688 assertFalse(dpms.isNotificationListenerServicePermitted(
4689 notPermittedListener, MANAGED_PROFILE_USER_ID));
4690 // System packages are always allowed (even if not in the whitelist)
4691 assertTrue(dpms.isNotificationListenerServicePermitted(
4692 systemListener, MANAGED_PROFILE_USER_ID));
4693
4694 // Setting an empty whitelist - only system listeners allowed
4695 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4696 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004697 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004698 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4699
4700 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4701 assertFalse(dpms.isNotificationListenerServicePermitted(
4702 permittedListener, MANAGED_PROFILE_USER_ID));
4703 assertFalse(dpms.isNotificationListenerServicePermitted(
4704 notPermittedListener, MANAGED_PROFILE_USER_ID));
4705 // System packages are always allowed (even if not in the whitelist)
4706 assertTrue(dpms.isNotificationListenerServicePermitted(
4707 systemListener, MANAGED_PROFILE_USER_ID));
4708
4709 // Setting a null whitelist - all listeners allowed
4710 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4711 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4712 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4713
4714 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4715 assertTrue(dpms.isNotificationListenerServicePermitted(
4716 permittedListener, MANAGED_PROFILE_USER_ID));
4717 assertTrue(dpms.isNotificationListenerServicePermitted(
4718 notPermittedListener, MANAGED_PROFILE_USER_ID));
4719 assertTrue(dpms.isNotificationListenerServicePermitted(
4720 systemListener, MANAGED_PROFILE_USER_ID));
4721 }
4722
4723 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4724 throws Exception {
4725 // Set up a managed profile
4726 final int MANAGED_PROFILE_USER_ID = 15;
4727 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4728 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4729 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4730
4731 final String nonSystemPackage = "non.system.package";
4732 int appId = 12345;
4733 setupPackageInPackageManager(
4734 nonSystemPackage,
4735 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4736 appId, /*flags=*/ 0);
4737
4738 final String systemListener = "system.package";
4739 setupPackageInPackageManager(
4740 systemListener,
4741 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4742 ++appId, ApplicationInfo.FLAG_SYSTEM);
4743
4744 // By default all packages are allowed (for all profiles)
4745 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4746
4747 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4748 assertTrue(dpms.isNotificationListenerServicePermitted(
4749 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4750 assertTrue(dpms.isNotificationListenerServicePermitted(
4751 systemListener, MANAGED_PROFILE_USER_ID));
4752 assertTrue(dpms.isNotificationListenerServicePermitted(
4753 nonSystemPackage, UserHandle.USER_SYSTEM));
4754 assertTrue(dpms.isNotificationListenerServicePermitted(
4755 systemListener, UserHandle.USER_SYSTEM));
4756
4757 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4758 // all allowed in primary profile
4759 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4760 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004761 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004762 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4763
4764 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4765 assertFalse(dpms.isNotificationListenerServicePermitted(
4766 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4767 assertTrue(dpms.isNotificationListenerServicePermitted(
4768 systemListener, MANAGED_PROFILE_USER_ID));
4769 assertTrue(dpms.isNotificationListenerServicePermitted(
4770 nonSystemPackage, UserHandle.USER_SYSTEM));
4771 assertTrue(dpms.isNotificationListenerServicePermitted(
4772 systemListener, UserHandle.USER_SYSTEM));
4773 }
4774
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004775 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004776 mServiceContext.packageName = mRealTestContext.getPackageName();
4777 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4778 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004779 setDeviceOwner();
4780
Pavel Grafov75c0a892017-05-18 17:28:27 +01004781 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004782 }
4783
4784 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004785 mServiceContext.packageName = mRealTestContext.getPackageName();
4786 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4787 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004788 setAsProfileOwner(admin1);
4789
Pavel Grafov75c0a892017-05-18 17:28:27 +01004790 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4791 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004792 }
4793
4794 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 mServiceContext.packageName = mRealTestContext.getPackageName();
4796 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4797 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004798 setAsProfileOwner(admin1);
4799
Pavel Grafov75c0a892017-05-18 17:28:27 +01004800 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4801 caller.packageName = "com.example.delegate";
4802 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4803 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004804
Pavel Grafov75c0a892017-05-18 17:28:27 +01004805 // Make caller a delegated cert installer.
4806 runAsCaller(mAdmin1Context, dpms,
4807 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004808
4809 verifyCanGetOwnerInstalledCaCerts(null, caller);
4810 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004811 }
4812
Rubin Xucc391c22018-01-02 20:37:35 +00004813 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004814 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4815 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004816 Bundle restriction = new Bundle();
4817 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4818
4819 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4820 RestrictionsListener listener = new RestrictionsListener(mContext);
4821 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4822 new Bundle());
4823 verifyDataSharingChangedBroadcast();
4824 }
4825
4826 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004827 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4828 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004829 Bundle restriction = new Bundle();
4830 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4831
4832 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4833 RestrictionsListener listener = new RestrictionsListener(mContext);
4834 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4835 restriction);
4836 verifyDataSharingChangedBroadcast();
4837 }
4838
4839 public void testDisallowSharingIntoProfileUnchanged() {
4840 RestrictionsListener listener = new RestrictionsListener(mContext);
4841 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4842 new Bundle());
4843 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4844 }
4845
4846 private void verifyDataSharingChangedBroadcast() {
4847 Intent expectedIntent = new Intent(
4848 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4849 expectedIntent.setPackage("com.android.managedprovisioning");
4850 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4851 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4852 MockUtils.checkIntent(expectedIntent),
4853 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4854 }
4855
yuemingwe3d9c092018-01-11 12:11:44 +00004856 public void testOverrideApnAPIsFailWithPO() throws Exception {
4857 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004858 ApnSetting apn = (new ApnSetting.Builder())
4859 .setApnName("test")
4860 .setEntryName("test")
4861 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4862 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004863 assertExpectException(SecurityException.class, null, () ->
4864 dpm.addOverrideApn(admin1, apn));
4865 assertExpectException(SecurityException.class, null, () ->
4866 dpm.updateOverrideApn(admin1, 0, apn));
4867 assertExpectException(SecurityException.class, null, () ->
4868 dpm.removeOverrideApn(admin1, 0));
4869 assertExpectException(SecurityException.class, null, () ->
4870 dpm.getOverrideApns(admin1));
4871 assertExpectException(SecurityException.class, null, () ->
4872 dpm.setOverrideApnsEnabled(admin1, false));
4873 assertExpectException(SecurityException.class, null, () ->
4874 dpm.isOverrideApnEnabled(admin1));
4875 }
4876
Robin Lee2c68dad2017-03-17 12:50:24 +00004877 private void verifyCanGetOwnerInstalledCaCerts(
4878 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004879 final String alias = "cert";
4880 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004881
4882 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004883 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004884 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4885 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004886 }
4887 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4888
4889 // caller: device admin or delegated certificate installer
4890 callerContext.applicationInfo = new ApplicationInfo();
4891 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4892
4893 // system_server
4894 final DpmMockContext serviceContext = mContext;
4895 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004896 getServices().addPackageContext(callerUser, admin1Context);
4897 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004898
4899 // Install a CA cert.
4900 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004901 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004902 .thenReturn(alias);
4903 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004904 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004905 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004906 });
4907
Pavel Grafov75c0a892017-05-18 17:28:27 +01004908 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4909 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4910 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004911 flushTasks();
4912
Robin Lee2c68dad2017-03-17 12:50:24 +00004913 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4914
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004915 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004916 runAsCaller(admin1Context, dpms, (dpm) -> {
4917 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004918 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004919 ownerInstalledCaCerts.addAll(installedCaCerts);
4920 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004921
4922 // Restarting the DPMS should not lose information.
4923 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004924 runAsCaller(admin1Context, dpms, (dpm) ->
4925 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004926
4927 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004928 runAsCaller(serviceContext, dpms, (dpm) -> {
4929 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004930
Robin Lee2c68dad2017-03-17 12:50:24 +00004931 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004932 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004933 });
4934
Pavel Grafov75c0a892017-05-18 17:28:27 +01004935 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4936 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4937 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004938 flushTasks();
4939
4940 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4941 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004942 runAsCaller(admin1Context, dpms, (dpm) -> {
4943 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4944 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004945 }
4946
Robin Lee2c68dad2017-03-17 12:50:24 +00004947 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4948 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004949 final String alias = "cert";
4950 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004951
4952 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004953 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004954 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4955 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004956 }
4957 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4958
4959 // caller: device admin or delegated certificate installer
4960 callerContext.applicationInfo = new ApplicationInfo();
4961 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4962
4963 // system_server
4964 final DpmMockContext serviceContext = mContext;
4965 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004966 getServices().addPackageContext(callerUser, admin1Context);
4967 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004968
4969 // Install a CA cert as caller
4970 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004971 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004972 .thenReturn(alias);
4973 assertTrue(dpm.installCaCert(callerName, caCert));
4974 });
4975
4976 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004977 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004978 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004979 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4980 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4981 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004982 flushTasks();
4983
Robin Lee2c68dad2017-03-17 12:50:24 +00004984 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004985 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004986
4987 runAsCaller(serviceContext, dpms, (dpm) -> {
4988 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4989 assertNotNull(ownerInstalledCaCerts);
4990 assertTrue(ownerInstalledCaCerts.isEmpty());
4991 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004992 }
4993
Eran Messeri94d56762017-12-21 20:50:54 +00004994 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4995 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4996 Arrays.sort(gotFlags);
4997 Arrays.sort(expectedFlags);
4998 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4999 }
5000
5001 public void testTranslationOfIdAttestationFlag() {
5002 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5003 int[] correspondingAttUtilsTypes = new int[]{
5004 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5005 AttestationUtils.ID_TYPE_MEID};
5006
5007 // Test translation of zero flags
5008 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5009
5010 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5011 // non-null array
5012 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5013
5014 // Test translation of a single flag
5015 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5016 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5017 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5018
5019 // Test translation of two flags
5020 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5021 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5022 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5023 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5024
5025 // Test translation of all three flags
5026 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5027 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5028 AttestationUtils.ID_TYPE_MEID});
5029 // Test translation of all three flags
5030 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5031 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5032 AttestationUtils.ID_TYPE_MEID});
5033 }
5034
arangelov08d534b2018-01-22 15:20:53 +00005035 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5036 setDeviceOwner();
5037 initializeDpms();
5038 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5039 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5040 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5041 }
5042
5043 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5044 DpmTestUtils.writeInputStreamToFile(
5045 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5046 getDeviceOwnerPoliciesFile());
5047 DpmTestUtils.writeInputStreamToFile(
5048 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5049 getDeviceOwnerFile());
5050 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5051 }
5052
5053 public void testRevertDeviceOwnership_deviceNotMigrated()
5054 throws Exception {
5055 DpmTestUtils.writeInputStreamToFile(
5056 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5057 getDeviceOwnerPoliciesFile());
5058 DpmTestUtils.writeInputStreamToFile(
5059 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5060 getDeviceOwnerFile());
5061 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5062 }
5063
5064 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5065 throws Exception {
5066 DpmTestUtils.writeInputStreamToFile(
5067 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5068 getDeviceOwnerPoliciesFile());
5069 DpmTestUtils.writeInputStreamToFile(
5070 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5071 getDeviceOwnerFile());
5072 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5073 }
5074
5075 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5076 setupProfileOwner();
5077 initializeDpms();
5078 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5079 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5080 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5081 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5082 }
5083
5084 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5085 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5086 UserHandle.USER_SYSTEM);
5087 DpmTestUtils.writeInputStreamToFile(
5088 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5089 getProfileOwnerPoliciesFile());
5090 DpmTestUtils.writeInputStreamToFile(
5091 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5092 getProfileOwnerFile());
5093 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5094 }
5095
5096 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5097 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5098 UserHandle.USER_SYSTEM);
5099 DpmTestUtils.writeInputStreamToFile(
5100 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5101 getProfileOwnerPoliciesFile());
5102 DpmTestUtils.writeInputStreamToFile(
5103 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5104 getProfileOwnerFile());
5105 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5106 }
5107
5108 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5109 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5110 UserHandle.USER_SYSTEM);
5111 DpmTestUtils.writeInputStreamToFile(
5112 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5113 getProfileOwnerPoliciesFile());
5114 DpmTestUtils.writeInputStreamToFile(
5115 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5116 getProfileOwnerFile());
5117 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5118 }
5119
Eran Messeribb271892018-10-17 18:27:50 +01005120 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5121 setupProfileOwner();
5122 configureContextForAccess(mContext, false);
5123
5124 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005125 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005126 }
5127
5128 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5129 setupProfileOwner();
5130 configureContextForAccess(mContext, false);
5131
5132 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005133 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005134 }
5135
5136 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5137 setupProfileOwner();
5138
5139 // This method will throw if the system context could not call
5140 // setProfileOwnerCanAccessDeviceIds successfully.
5141 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5142 }
5143
5144 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5145 when(context.spiedContext.checkCallingPermission(
5146 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5147 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5148 : PackageManager.PERMISSION_DENIED);
5149 }
5150
5151 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5152 setupProfileOwner();
5153
5154 final long ident = mServiceContext.binder.clearCallingIdentity();
5155 configureContextForAccess(mServiceContext, true);
5156
5157 mServiceContext.binder.callingUid =
5158 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5159 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5160 try {
5161 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005162 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005163 });
5164 } finally {
5165 mServiceContext.binder.restoreCallingIdentity(ident);
5166 }
5167 }
5168
5169 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5170 throws Exception {
5171 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5172 setupDeviceOwner();
5173 configureContextForAccess(mContext, false);
5174
5175 // Device owner should be allowed to request Device ID attestation.
5176 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5177 DpmMockContext.CALLER_SYSTEM_USER_UID);
5178
5179 // Another package must not be allowed to request Device ID attestation.
5180 assertExpectException(SecurityException.class, null,
5181 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5182 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5183 // Another component that is not the admin must not be allowed to request Device ID
5184 // attestation.
5185 assertExpectException(SecurityException.class, null,
5186 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5187 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5188 }
5189
5190 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5191 throws Exception {
5192 configureContextForAccess(mContext, false);
5193
5194 // Make sure a security exception is thrown if the device has no profile owner.
5195 assertExpectException(SecurityException.class, null,
5196 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5197 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5198
5199 setupProfileOwner();
5200 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5201
5202 // The profile owner is allowed to request Device ID attestation.
5203 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5204 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5205 DpmMockContext.CALLER_UID);
5206 // But not another package.
5207 assertExpectException(SecurityException.class, null,
5208 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5209 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5210 // Or another component which is not the admin.
5211 assertExpectException(SecurityException.class, null,
5212 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5213 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5214 }
5215
5216 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5217 final long ident = mServiceContext.binder.clearCallingIdentity();
5218
5219 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5220 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5221 try {
5222 runAsCaller(mServiceContext, dpms, action);
5223 } finally {
5224 mServiceContext.binder.restoreCallingIdentity(ident);
5225 }
5226 }
5227
5228 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5229 setupProfileOwner();
5230 markDelegatedCertInstallerAsInstalled();
5231
5232 // Configure a delegated cert installer.
5233 runAsCaller(mServiceContext, dpms,
5234 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5235 Arrays.asList(DELEGATION_CERT_INSTALL)));
5236
5237 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5238
5239 // Make sure that the profile owner can still request Device ID attestation.
5240 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5241 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5242 DpmMockContext.CALLER_UID);
5243
5244 runAsDelegatedCertInstaller(dpm -> {
5245 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5246 DpmMockContext.DELEGATE_PACKAGE_NAME,
5247 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5248 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5249 });
5250 }
5251
5252 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5253 throws Exception {
5254 setupProfileOwner();
5255 markDelegatedCertInstallerAsInstalled();
5256
5257 // Configure a delegated cert installer.
5258 runAsCaller(mServiceContext, dpms,
5259 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5260 Arrays.asList(DELEGATION_CERT_INSTALL)));
5261
5262
5263 assertExpectException(SecurityException.class, null,
5264 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5265 admin1.getPackageName(),
5266 DpmMockContext.CALLER_UID));
5267
5268 runAsDelegatedCertInstaller(dpm -> {
5269 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5270 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5271 DpmMockContext.DELEGATE_PACKAGE_NAME,
5272 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5273 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5274 });
5275 }
5276
Bernard Chaue9586552018-11-29 10:59:31 +00005277 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5278 assertThrows(SecurityException.class,
5279 () -> new DevicePolicyManagerTestable(
5280 mServiceContext,
5281 dpms,
5282 /* parentInstance= */ true)
5283 .getPasswordComplexity());
5284 }
5285
5286 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5287 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5288 .thenReturn(false);
5289 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5290 }
5291
5292 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5293 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5294 .thenReturn(true);
5295 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5296 }
5297
5298
5299 public void testGetPasswordComplexity_currentUserNoPassword() {
5300 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5301 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005302 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005303 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5304 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5305
5306 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5307 }
5308
5309 public void testGetPasswordComplexity_currentUserHasPassword() {
5310 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5311 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005312 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005313 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5314 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005315 when(getServices().lockSettingsInternal
5316 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5317 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005318
5319 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5320 }
5321
5322 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5323 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5324 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005325 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005326
5327 UserInfo parentUser = new UserInfo();
5328 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5329 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5330 .thenReturn(parentUser.id);
5331
Rubin Xu19854862019-08-15 16:37:23 +01005332 when(getServices().lockSettingsInternal
5333 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5334 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
5335 when(getServices().lockSettingsInternal
5336 .getUserPasswordMetrics(parentUser.id))
5337 .thenReturn(PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005338
5339 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5340 }
5341
yuemingwd2bfbc82019-01-02 11:42:25 +00005342 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5343 setAsProfileOwner(admin1);
5344 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5345 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5346 }
5347
5348 public void testCrossProfileCalendarPackages_reopenDpms() {
5349 setAsProfileOwner(admin1);
5350 dpm.setCrossProfileCalendarPackages(admin1, null);
5351 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5352 assertTrue(packages == null);
5353 initializeDpms();
5354 packages = dpm.getCrossProfileCalendarPackages(admin1);
5355 assertTrue(packages == null);
5356
5357 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5358 packages = dpm.getCrossProfileCalendarPackages(admin1);
5359 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5360 initializeDpms();
5361 packages = dpm.getCrossProfileCalendarPackages(admin1);
5362 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5363
5364 final String dummyPackageName = "test";
5365 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5366 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5367 packages = dpm.getCrossProfileCalendarPackages(admin1);
5368 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5369 initializeDpms();
5370 packages = dpm.getCrossProfileCalendarPackages(admin1);
5371 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5372 }
5373
5374 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5375 assertTrue(expected != null);
5376 assertTrue(actual != null);
5377 assertTrue(expected.containsAll(actual));
5378 assertTrue(actual.containsAll(expected));
5379 }
5380
yuemingwdded98f2019-01-30 17:08:12 +00005381 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5382 setAsProfileOwner(admin1);
5383 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5384 when(getServices().settings.settingsSecureGetIntForUser(
5385 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5386 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5387 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5388 }
5389
5390 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5391 final String testPackage = "TEST_PACKAGE";
5392 setAsProfileOwner(admin1);
5393 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5394 when(getServices().settings.settingsSecureGetIntForUser(
5395 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5396 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5397 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5398 }
5399
5400 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5401 final String testPackage = "TEST_PACKAGE";
5402 setAsProfileOwner(admin1);
5403 dpm.setCrossProfileCalendarPackages(admin1, null);
5404 when(getServices().settings.settingsSecureGetIntForUser(
5405 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5406 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5407 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5408 }
5409
Eran Messeribb271892018-10-17 18:27:50 +01005410 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5411 final long ident = mServiceContext.binder.clearCallingIdentity();
5412 mServiceContext.binder.callingUid =
5413 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5414 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005415 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005416 });
5417 mServiceContext.binder.restoreCallingIdentity(ident);
5418 }
5419
arangelov08d534b2018-01-22 15:20:53 +00005420 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5421 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5422 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5423 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5424
5425 final long ident = mServiceContext.binder.clearCallingIdentity();
5426 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5427 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5428 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5429 // To simulate a reboot, we just reinitialize dpms and call systemReady
5430 initializeDpms();
5431
5432 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5433 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5434 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5435 assertTrue(dpm.isAdminActive(admin1));
5436 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5437 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5438
5439 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5440 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5441 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5442 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5443
5444 mServiceContext.binder.restoreCallingIdentity(ident);
5445 }
5446
5447 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5448 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5449 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5450 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5451
5452 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5453 DpmMockContext.CALLER_SYSTEM_USER_UID);
5454 setUpPackageManagerForAdmin(admin1, uid);
5455 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5456 // To simulate a reboot, we just reinitialize dpms and call systemReady
5457 initializeDpms();
5458
5459 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5460 assertTrue(dpm.isAdminActive(admin1));
5461 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5462 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5463 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5464 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5465 }
5466
5467 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5468 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5469 metadataManager.deleteMetadataFile();
5470
5471 final TransferOwnershipMetadataManager.Metadata metadata =
5472 new TransferOwnershipMetadataManager.Metadata(
5473 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5474 callerUserHandle,
5475 adminType);
5476 metadataManager.saveMetadataFile(metadata);
5477 }
5478
5479 private File getDeviceOwnerFile() {
5480 return dpms.mOwners.getDeviceOwnerFile();
5481 }
5482
5483 private File getProfileOwnerFile() {
5484 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5485 }
5486
5487 private File getProfileOwnerPoliciesFile() {
5488 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5489 DpmMockContext.CALLER_USER_HANDLE);
5490 return getPoliciesFile(parentDir);
5491 }
5492
5493 private File getDeviceOwnerPoliciesFile() {
5494 return getPoliciesFile(getServices().systemUserDataDir);
5495 }
5496
5497 private File getPoliciesFile(File parentDir) {
5498 return new File(parentDir, "device_policies.xml");
5499 }
5500
5501 private InputStream getRawStream(@RawRes int id) {
5502 return mRealTestContext.getResources().openRawResource(id);
5503 }
5504
Victor Chang3e794af2016-03-04 13:48:17 +00005505 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005506 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005507 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5508 dpms.notifyChangeToContentObserver(
5509 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5510 }
5511
5512 private void assertProvisioningAllowed(String action, boolean expected) {
5513 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5514 dpm.isProvisioningAllowed(action));
5515 }
Tony Mak2f26b792016-11-28 17:54:51 +00005516
Nicolas Prevot45d29072017-01-18 16:11:19 +00005517 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5518 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005519 final String previousPackageName = mContext.packageName;
5520 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005521
5522 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5523 mContext.packageName = packageName;
5524 mMockContext.binder.callingUid = uid;
5525 assertProvisioningAllowed(action, expected);
5526
5527 // Set the previous package name / calling uid to go back to the initial state.
5528 mContext.packageName = previousPackageName;
5529 mMockContext.binder.callingUid = previousUid;
5530 }
5531
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005532 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005533 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5534 }
5535
5536 private void assertCheckProvisioningPreCondition(
5537 String action, String packageName, int provisioningCondition) {
5538 assertEquals("checkProvisioningPreCondition("
5539 + action + ", " + packageName + ") returning unexpected result",
5540 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005541 }
5542
Tony Mak2f26b792016-11-28 17:54:51 +00005543 /**
5544 * Setup a managed profile with the specified admin and its uid.
5545 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5546 * @param adminUid uid of the admin package.
5547 * @param copyFromAdmin package information for {@code admin} will be built based on this
5548 * component's information.
5549 */
5550 private void addManagedProfile(
5551 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5552 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005553 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005554 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5555 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5556 dpm.setActiveAdmin(admin, false, userId);
5557 assertTrue(dpm.setProfileOwner(admin, null, userId));
5558 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5559 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005560
5561 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005562 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005563 */
Robin Leeabaa0692017-02-20 20:54:22 +00005564 private static StringParceledListSlice asSlice(String[] s) {
5565 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005566 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005567
5568 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005569 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5570 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005571
Robin Lee2c68dad2017-03-17 12:50:24 +00005572 // We can't let exceptions happen on the background thread. Throw them here if they happen
5573 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005574 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005575 }
Victor Chang3e794af2016-03-04 13:48:17 +00005576}