blob: 1cec3df3582c16dca2176b230c73eeb9b5ddc828 [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 Xua58125d2019-09-06 20:11:48 +010096import com.android.internal.widget.LockscreenCredential;
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
2653 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2654 // uses separate challenge.
2655 public void testSetMaximumTimeToLockProfile() throws Exception {
2656 final int PROFILE_USER = 15;
2657 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2658 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2659 mContext.binder.callingUid = PROFILE_ADMIN;
2660 final DevicePolicyManagerInternal dpmi =
2661 LocalServices.getService(DevicePolicyManagerInternal.class);
2662
2663 dpm.setMaximumTimeToLock(admin1, 0);
2664
2665 reset(getServices().powerManagerInternal);
2666 reset(getServices().settings);
2667
2668 // First add timeout for the profile.
2669 dpm.setMaximumTimeToLock(admin1, 10);
2670 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2671
2672 reset(getServices().powerManagerInternal);
2673 reset(getServices().settings);
2674
2675 // Add separate challenge
2676 when(getServices().lockPatternUtils
2677 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2678 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2679
2680 verifyScreenTimeoutCall(10L, PROFILE_USER);
2681 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2682
2683 reset(getServices().powerManagerInternal);
2684 reset(getServices().settings);
2685
2686 // Remove the timeout.
2687 dpm.setMaximumTimeToLock(admin1, 0);
2688 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2689 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2690
2691 reset(getServices().powerManagerInternal);
2692 reset(getServices().settings);
2693
2694 // Add it back.
2695 dpm.setMaximumTimeToLock(admin1, 10);
2696 verifyScreenTimeoutCall(10L, PROFILE_USER);
2697 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2698
2699 reset(getServices().powerManagerInternal);
2700 reset(getServices().settings);
2701
2702 // Remove separate challenge.
2703 reset(getServices().lockPatternUtils);
2704 when(getServices().lockPatternUtils
2705 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2706 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002707 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002708
2709 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2710 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2711
2712 reset(getServices().powerManagerInternal);
2713 reset(getServices().settings);
2714
2715 // Remove the timeout.
2716 dpm.setMaximumTimeToLock(admin1, 0);
2717 verifyScreenTimeoutCall(null, PROFILE_USER);
2718 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002719 }
2720
Michal Karpinski943aabd2016-10-06 11:09:25 +01002721 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2722 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2723 setupDeviceOwner();
2724 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2725
Michal Karpinskid084ca52017-01-18 15:54:18 +00002726 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2727 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2728 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2729 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2730 - ONE_MINUTE;
2731
2732 // verify that the minimum timeout cannot be modified on user builds (system property is
2733 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002734 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002735
2736 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2737 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2738 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2739
Pavel Grafov75c0a892017-05-18 17:28:27 +01002740 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002741
2742 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002743 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002744
Michal Karpinskid084ca52017-01-18 15:54:18 +00002745 // reset to default (0 means the admin is not participating, so default should be returned)
2746 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002747
2748 // aggregation should be the default if unset by any admin
2749 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2750 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2751
2752 // admin not participating by default
2753 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2754
2755 //clamping from the top
2756 dpm.setRequiredStrongAuthTimeout(admin1,
2757 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2758 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2759 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2760 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2761 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2762
Michal Karpinskid084ca52017-01-18 15:54:18 +00002763 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002764 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2765 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2766 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2767 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2768
2769 // clamping from the bottom
2770 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2771 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2772 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2773
Michal Karpinskid084ca52017-01-18 15:54:18 +00002774 // values within range
2775 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2776 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2777 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2778
2779 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2780 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2781 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002782
2783 // reset to default
2784 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2785 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2786 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2787 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2788
2789 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002790 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2791 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002792 }
2793
Pavel Grafov28939982017-10-03 15:11:52 +01002794 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002795 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002796 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002797 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002798 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002799 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002800 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002801 }
Pavel Grafov28939982017-10-03 15:11:52 +01002802 }
2803
2804 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002805 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2806 // UnfinishedVerificationException.
2807 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002808
Esteban Talavera01576862016-12-15 11:16:44 +00002809 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002811 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002812 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002813 .thenReturn(false);
2814 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002815 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2816 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002817 .thenReturn(true);
2818 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2819
2820 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002821 }
Victor Chang3e794af2016-03-04 13:48:17 +00002822
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002823 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2824 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002825 mContext.packageName = admin1.getPackageName();
2826 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2828 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2829 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2830 false);
2831 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2832 }
2833
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002834 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2835 setup_DeviceAdminFeatureOff();
2836 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2837 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2838 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2839 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2840 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2841 assertCheckProvisioningPreCondition(
2842 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2843 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2844 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2845 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2846 }
2847
Esteban Talavera01576862016-12-15 11:16:44 +00002848 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002849 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002850 .thenReturn(false);
2851 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002852 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2853 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002854 .thenReturn(true);
2855 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2856
2857 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002858 }
Victor Chang3e794af2016-03-04 13:48:17 +00002859
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002860 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2861 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002862 mContext.packageName = admin1.getPackageName();
2863 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002864 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2865 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2867 false);
2868 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2869
2870 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002871 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002872 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2873 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2874 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2875 true);
2876 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2877 }
2878
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002879 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2880 setup_ManagedProfileFeatureOff();
2881 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2882 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2883 DevicePolicyManager.CODE_OK);
2884 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2885 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2886 assertCheckProvisioningPreCondition(
2887 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2888 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2889 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2890 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2891
2892 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002893 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2895 DevicePolicyManager.CODE_OK);
2896 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2897 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2898 assertCheckProvisioningPreCondition(
2899 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2900 DevicePolicyManager.CODE_OK);
2901 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2902 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2903 }
2904
Esteban Talavera01576862016-12-15 11:16:44 +00002905 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002906 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002907 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002908 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2909 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002910 .thenReturn(true);
2911 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2912
2913 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 }
Victor Chang3e794af2016-03-04 13:48:17 +00002915
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002916 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2917 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002918 mContext.packageName = admin1.getPackageName();
2919 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2922 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2923 false /* because of non-split user */);
2924 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2925 false /* because of non-split user */);
2926 }
2927
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002928 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002929 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002930 setup_nonSplitUser_firstBoot_primaryUser();
2931 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2932 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2933 DevicePolicyManager.CODE_OK);
2934 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2935 DevicePolicyManager.CODE_OK);
2936 assertCheckProvisioningPreCondition(
2937 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2938 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2939 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2940 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2941 }
2942
Esteban Talavera01576862016-12-15 11:16:44 +00002943 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002944 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002945 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002946 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2947 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002948 .thenReturn(true);
2949 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2950
2951 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002952 }
Victor Chang3e794af2016-03-04 13:48:17 +00002953
Nicolas Prevot45d29072017-01-18 16:11:19 +00002954 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2955 setDeviceOwner();
2956 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2957 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2958 }
2959
2960 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2961 setup_nonSplitUser_withDo_primaryUser();
2962 final int MANAGED_PROFILE_USER_ID = 18;
2963 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2964 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002965 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002966 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002967 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002968 true)).thenReturn(true);
2969 }
2970
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002971 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2972 throws Exception {
2973 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002974 mContext.packageName = admin1.getPackageName();
2975 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002976 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2977 false/* because of completed device setup */);
2978 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2979 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2980 false/* because of non-split user */);
2981 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2982 false/* because of non-split user */);
2983 }
2984
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002985 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2986 throws Exception {
2987 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2988 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2989 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2990 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2991 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2992 DevicePolicyManager.CODE_OK);
2993 assertCheckProvisioningPreCondition(
2994 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2995 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2996 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2997 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2998 }
2999
Nicolas Prevot45d29072017-01-18 16:11:19 +00003000 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3001 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003002 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003003 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3004
3005 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3006 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003007 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003008
3009 // COMP mode is allowed.
3010 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3011 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003012 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003013
Nicolas Prevot45d29072017-01-18 16:11:19 +00003014 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003015 assertCheckProvisioningPreCondition(
3016 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003017 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003018 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003019 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3020 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3021 }
Esteban Talavera01576862016-12-15 11:16:44 +00003022
Nicolas Prevot45d29072017-01-18 16:11:19 +00003023 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3024 setup_nonSplitUser_withDo_primaryUser();
3025 mContext.packageName = admin1.getPackageName();
3026 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3027 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3028 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003029 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003030 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3031 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3032 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003033 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003034 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3035 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3036 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3037 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3038 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003039 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003040 assertCheckProvisioningPreCondition(
3041 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003042 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003043 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003044 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3045 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3046 }
Esteban Talavera01576862016-12-15 11:16:44 +00003047
Nicolas Prevot45d29072017-01-18 16:11:19 +00003048 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3049 throws Exception {
3050 setup_nonSplitUser_withDo_primaryUser();
3051 mContext.packageName = admin1.getPackageName();
3052 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003053 // The DO should not be allowed to initiate provisioning if the restriction is set by
3054 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003055 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003056 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3057 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3058 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003059 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003060 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3061 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3062 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3063 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3064 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3066
3067 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003068 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003069 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003070 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3072 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3073 }
3074
3075 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3076 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3077 mContext.packageName = admin1.getPackageName();
3078 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3079
3080 // We can delete the managed profile to create a new one, so provisioning is allowed.
3081 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3082 DevicePolicyManager.CODE_OK);
3083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3084 assertCheckProvisioningPreCondition(
3085 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3086 DpmMockContext.ANOTHER_PACKAGE_NAME,
3087 DevicePolicyManager.CODE_OK);
3088 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3089 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3090 }
3091
3092 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3093 throws Exception {
3094 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3095 mContext.packageName = admin1.getPackageName();
3096 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003097 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003098 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3099 eq(UserHandle.SYSTEM)))
3100 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003101 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003102 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3103 eq(UserHandle.SYSTEM)))
3104 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003105
3106 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003107 assertCheckProvisioningPreCondition(
3108 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3109 DpmMockContext.ANOTHER_PACKAGE_NAME,
3110 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3111 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3112 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003113
3114 // But the device owner can still do it because it has set the restriction itself.
3115 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3116 DevicePolicyManager.CODE_OK);
3117 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003118 }
3119
3120 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003121 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003122 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003123 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3124 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003125 .thenReturn(false);
3126 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3127
3128 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003129 }
Victor Chang3e794af2016-03-04 13:48:17 +00003130
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003131 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3132 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003133 mContext.packageName = admin1.getPackageName();
3134 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003135 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3136 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3137 false /* because canAddMoreManagedProfiles returns false */);
3138 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3139 true);
3140 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3141 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003142 }
3143
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003144 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3145 throws Exception {
3146 setup_splitUser_firstBoot_systemUser();
3147 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3148 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3149 DevicePolicyManager.CODE_OK);
3150 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003151 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003152 assertCheckProvisioningPreCondition(
3153 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3154 DevicePolicyManager.CODE_OK);
3155 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3156 DevicePolicyManager.CODE_SYSTEM_USER);
3157 }
3158
Esteban Talavera01576862016-12-15 11:16:44 +00003159 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003160 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003161 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003162 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3163 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003164 .thenReturn(false);
3165 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3166
3167 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003168 }
Victor Chang3e794af2016-03-04 13:48:17 +00003169
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003170 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3171 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003172 mContext.packageName = admin1.getPackageName();
3173 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3175 true/* it's undefined behavior. Can be changed into false in the future */);
3176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3177 false /* because canAddMoreManagedProfiles returns false */);
3178 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3179 true/* it's undefined behavior. Can be changed into false in the future */);
3180 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3181 false/* because calling uid is system user */);
3182 }
3183
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003184 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3185 throws Exception {
3186 setup_splitUser_afterDeviceSetup_systemUser();
3187 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3188 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3189 DevicePolicyManager.CODE_OK);
3190 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003191 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003192 assertCheckProvisioningPreCondition(
3193 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3194 DevicePolicyManager.CODE_OK);
3195 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3196 DevicePolicyManager.CODE_SYSTEM_USER);
3197 }
3198
Esteban Talavera01576862016-12-15 11:16:44 +00003199 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003200 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003201 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003202 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3203 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003204 true)).thenReturn(true);
3205 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3206
3207 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003208 }
Victor Chang3e794af2016-03-04 13:48:17 +00003209
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003210 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3211 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003212 mContext.packageName = admin1.getPackageName();
3213 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003214 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3215 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3216 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3217 true);
3218 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003219 }
3220
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003221 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003222 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003223 setup_splitUser_firstBoot_primaryUser();
3224 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3225 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3226 DevicePolicyManager.CODE_OK);
3227 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3228 DevicePolicyManager.CODE_OK);
3229 assertCheckProvisioningPreCondition(
3230 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3231 DevicePolicyManager.CODE_OK);
3232 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3233 DevicePolicyManager.CODE_OK);
3234 }
3235
Esteban Talavera01576862016-12-15 11:16:44 +00003236 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003237 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003238 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003239 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3240 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003241 true)).thenReturn(true);
3242 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3243
3244 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003245 }
Victor Chang3e794af2016-03-04 13:48:17 +00003246
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003247 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3248 throws Exception {
3249 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003250 mContext.packageName = admin1.getPackageName();
3251 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003252 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3253 true/* it's undefined behavior. Can be changed into false in the future */);
3254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3255 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3256 true/* it's undefined behavior. Can be changed into false in the future */);
3257 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3258 false/* because user setup completed */);
3259 }
3260
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003261 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003262 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003263 setup_splitUser_afterDeviceSetup_primaryUser();
3264 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3265 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3266 DevicePolicyManager.CODE_OK);
3267 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3268 DevicePolicyManager.CODE_OK);
3269 assertCheckProvisioningPreCondition(
3270 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3271 DevicePolicyManager.CODE_OK);
3272 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3273 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3274 }
3275
Esteban Talavera01576862016-12-15 11:16:44 +00003276 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003277 setDeviceOwner();
3278
Pavel Grafov75c0a892017-05-18 17:28:27 +01003279 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003280 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003281 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3282 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003283 .thenReturn(false);
3284 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3285
3286 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003287 }
Victor Chang3e794af2016-03-04 13:48:17 +00003288
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003289 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3290 throws Exception {
3291 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003292 mContext.packageName = admin1.getPackageName();
3293 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003294 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3295 false /* can't provision managed profile on system user */);
3296 }
3297
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003298 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003299 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003300 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3301 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3302 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3303 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3304 }
3305
3306 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003307 setDeviceOwner();
3308
Pavel Grafov75c0a892017-05-18 17:28:27 +01003309 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003310 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003311 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3312 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003313 true)).thenReturn(true);
3314 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3315
3316 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003317 }
Victor Chang3e794af2016-03-04 13:48:17 +00003318
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003319 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3320 throws Exception {
3321 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003322 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3323 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003324 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3325 }
3326
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003327 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003328 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003329 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3330 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003331
3332 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003333 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3334 DevicePolicyManager.CODE_OK);
3335 }
3336
3337 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003338 setDeviceOwner();
3339
Pavel Grafov75c0a892017-05-18 17:28:27 +01003340 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003341 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003342 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3343 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003344 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3345 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003346 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003347 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003348 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003349 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003350 true)).thenReturn(true);
3351 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3352
3353 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003354 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003355
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003356 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3357 throws Exception {
3358 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003359 mContext.packageName = admin1.getPackageName();
3360 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003361 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3362 }
3363
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003364 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3365 throws Exception {
3366 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3367 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3368 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3369 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3370 }
3371
3372 public void testCheckProvisioningPreCondition_permission() {
3373 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003374 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3375 () -> dpm.checkProvisioningPreCondition(
3376 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003377 }
3378
Victor Chang3577ed22016-08-25 18:49:26 +01003379 public void testForceUpdateUserSetupComplete_permission() {
3380 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003381 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3382 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003383 }
3384
3385 public void testForceUpdateUserSetupComplete_systemUser() {
3386 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3387 // GIVEN calling from user 20
3388 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003389 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3390 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003391 }
3392
3393 public void testForceUpdateUserSetupComplete_userbuild() {
3394 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3395 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3396
3397 final int userId = UserHandle.USER_SYSTEM;
3398 // GIVEN userComplete is false in SettingsProvider
3399 setUserSetupCompleteForUser(false, userId);
3400
3401 // GIVEN userComplete is true in DPM
3402 DevicePolicyManagerService.DevicePolicyData userData =
3403 new DevicePolicyManagerService.DevicePolicyData(userId);
3404 userData.mUserSetupComplete = true;
3405 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3406
3407 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003408 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003409
3410 assertTrue(dpms.hasUserSetupCompleted());
3411
3412 dpm.forceUpdateUserSetupComplete();
3413
3414 // THEN the state in dpms is not changed
3415 assertTrue(dpms.hasUserSetupCompleted());
3416 }
3417
3418 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3419 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3420 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3421
3422 final int userId = UserHandle.USER_SYSTEM;
3423 // GIVEN userComplete is false in SettingsProvider
3424 setUserSetupCompleteForUser(false, userId);
3425
3426 // GIVEN userComplete is true in DPM
3427 DevicePolicyManagerService.DevicePolicyData userData =
3428 new DevicePolicyManagerService.DevicePolicyData(userId);
3429 userData.mUserSetupComplete = true;
3430 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3431
3432 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003433 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003434
3435 assertTrue(dpms.hasUserSetupCompleted());
3436
3437 dpm.forceUpdateUserSetupComplete();
3438
3439 // THEN the state in dpms is not changed
3440 assertFalse(dpms.hasUserSetupCompleted());
3441 }
3442
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003443 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003444 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003445 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003446
3447 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3448 runAsCaller(mAdmin1Context, dpms, dpm -> {
3449 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3450 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003451 }
3452
3453 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3454 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3455 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003456
3457 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3458 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003459 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003460 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3461 .thenReturn(true);
3462
3463 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003464 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003465
3466 // Enabling logging should not change the timestamp.
3467 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003468 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003469 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003470 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003471 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003472 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003473
3474 // Retrieving the logs should update the timestamp.
3475 final long beforeRetrieval = System.currentTimeMillis();
3476 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003477 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003478 final long afterRetrieval = System.currentTimeMillis();
3479 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3480 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3481
3482 // Retrieving the pre-boot logs should update the timestamp.
3483 Thread.sleep(2);
3484 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003485 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003486 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3487
3488 // Checking the timestamp again should not change it.
3489 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003490 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003491
3492 // Retrieving the logs again should update the timestamp.
3493 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003494 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003495 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3496
3497 // Disabling logging should not change the timestamp.
3498 Thread.sleep(2);
3499 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003500 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003501
3502 // Restarting the DPMS should not lose the timestamp.
3503 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003504 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003505
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003506 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3507 mContext.binder.callingUid = 1234567;
3508 mContext.callerPermissions.add(permission.MANAGE_USERS);
3509 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3510 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3511
3512 // System can retrieve the timestamp.
3513 mContext.binder.clearCallingIdentity();
3514 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3515
3516 // Removing the device owner should clear the timestamp.
3517 clearDeviceOwner();
3518 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003519 }
3520
yuemingw0de748d2017-11-15 19:22:27 +00003521 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3522 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3523 setupDeviceOwner();
3524 assertExpectException(SecurityException.class, null, () ->
3525 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3526 }
3527
yuemingwc0281f12018-03-28 15:58:49 +01003528 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003529 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3530 setupDeviceOwner();
3531 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003532 verify(getServices().settings).settingsSystemPutStringForUser(
3533 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3534 }
3535
3536 public void testSetSystemSettingWithPO() throws Exception {
3537 setupProfileOwner();
3538 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3539 verify(getServices().settings).settingsSystemPutStringForUser(
3540 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003541 }
3542
yuemingwe43cdf72017-10-12 16:52:11 +01003543 public void testSetTime() throws Exception {
3544 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3545 setupDeviceOwner();
3546 dpm.setTime(admin1, 0);
3547 verify(getServices().alarmManager).setTime(0);
3548 }
3549
3550 public void testSetTimeFailWithPO() throws Exception {
3551 setupProfileOwner();
3552 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3553 }
3554
3555 public void testSetTimeWithAutoTimeOn() throws Exception {
3556 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3557 setupDeviceOwner();
3558 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3559 .thenReturn(1);
3560 assertFalse(dpm.setTime(admin1, 0));
3561 }
3562
3563 public void testSetTimeZone() throws Exception {
3564 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3565 setupDeviceOwner();
3566 dpm.setTimeZone(admin1, "Asia/Shanghai");
3567 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3568 }
3569
3570 public void testSetTimeZoneFailWithPO() throws Exception {
3571 setupProfileOwner();
3572 assertExpectException(SecurityException.class, null,
3573 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3574 }
3575
3576 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3577 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3578 setupDeviceOwner();
3579 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3580 .thenReturn(1);
3581 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3582 }
3583
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003584 public void testGetLastBugReportRequestTime() throws Exception {
3585 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3586 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003587
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003588 mContext.packageName = admin1.getPackageName();
3589 mContext.applicationInfo = new ApplicationInfo();
3590 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3591 .thenReturn(Color.WHITE);
3592 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3593 anyObject())).thenReturn(Color.WHITE);
3594
Esteban Talaverad36dd152016-12-15 08:51:45 +00003595 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3596 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003597 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003598
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003599 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003600 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003601
3602 // Requesting a bug report should update the timestamp.
3603 final long beforeRequest = System.currentTimeMillis();
3604 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003605 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003606 final long afterRequest = System.currentTimeMillis();
3607 assertTrue(bugReportRequestTime >= beforeRequest);
3608 assertTrue(bugReportRequestTime <= afterRequest);
3609
3610 // Checking the timestamp again should not change it.
3611 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003612 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003613
3614 // Restarting the DPMS should not lose the timestamp.
3615 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003616 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003617
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003618 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3619 mContext.binder.callingUid = 1234567;
3620 mContext.callerPermissions.add(permission.MANAGE_USERS);
3621 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3622 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3623
3624 // System can retrieve the timestamp.
3625 mContext.binder.clearCallingIdentity();
3626 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3627
3628 // Removing the device owner should clear the timestamp.
3629 clearDeviceOwner();
3630 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003631 }
3632
3633 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3634 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3635 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003636 mContext.packageName = admin1.getPackageName();
3637 mContext.applicationInfo = new ApplicationInfo();
3638 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3639 .thenReturn(Color.WHITE);
3640 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3641 anyObject())).thenReturn(Color.WHITE);
3642
3643 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3644 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003645 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003646 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003647 .thenReturn(true);
3648
3649 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003650 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003651
3652 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3653 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003654 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003655
3656 // Enabling logging should not change the timestamp.
3657 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003658 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003659
3660 // Retrieving the logs should update the timestamp.
3661 final long beforeRetrieval = System.currentTimeMillis();
3662 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003663 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003664 final long afterRetrieval = System.currentTimeMillis();
3665 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3666 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3667
3668 // Checking the timestamp again should not change it.
3669 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003670 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003671
3672 // Retrieving the logs again should update the timestamp.
3673 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003674 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003675 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3676
3677 // Disabling logging should not change the timestamp.
3678 Thread.sleep(2);
3679 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003680 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003681
3682 // Restarting the DPMS should not lose the timestamp.
3683 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003684 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3685
3686 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3687 mContext.binder.callingUid = 1234567;
3688 mContext.callerPermissions.add(permission.MANAGE_USERS);
3689 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3690 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3691
3692 // System can retrieve the timestamp.
3693 mContext.binder.clearCallingIdentity();
3694 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3695
3696 // Removing the device owner should clear the timestamp.
3697 clearDeviceOwner();
3698 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003699 }
3700
Tony Mak2f26b792016-11-28 17:54:51 +00003701 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3702 // Setup device owner.
3703 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3704 setupDeviceOwner();
3705
3706 // Only device owner is setup, the result list should be empty.
3707 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3708 MoreAsserts.assertEmpty(targetUsers);
3709
3710 // Setup a managed profile managed by the same admin.
3711 final int MANAGED_PROFILE_USER_ID = 15;
3712 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3713 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3714
3715 // Add a secondary user, it should never talk with.
3716 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003717 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003718
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003719 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3720 // other.
3721 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3722 MoreAsserts.assertEmpty(targetUsers);
3723
3724 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3725 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3726 MoreAsserts.assertEmpty(targetUsers);
3727
3728 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003729 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003730 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3731 dpm.setAffiliationIds(admin1, userAffiliationIds);
3732
3733 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3734 dpm.setAffiliationIds(admin1, userAffiliationIds);
3735
Tony Mak2f26b792016-11-28 17:54:51 +00003736 // Calling from device owner admin, the result list should just contain the managed
3737 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003738 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003739 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3740 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3741
3742 // Calling from managed profile admin, the result list should just contain the system
3743 // user id.
3744 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3745 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3746 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003747
3748 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003749 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003750
3751 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3752 // to each other.
3753 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3754 MoreAsserts.assertEmpty(targetUsers);
3755
3756 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3757 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3758 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003759 }
3760
3761 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3762 // Setup a device owner.
3763 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3764 setupDeviceOwner();
3765
3766 // Set up a managed profile managed by different package.
3767 final int MANAGED_PROFILE_USER_ID = 15;
3768 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3769 final ComponentName adminDifferentPackage =
3770 new ComponentName("another.package", "whatever.class");
3771 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3772
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003773 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003774 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003775 dpm.setAffiliationIds(admin1, userAffiliationIds);
3776
3777 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3778 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3779
Tony Mak2f26b792016-11-28 17:54:51 +00003780 // Calling from device owner admin, we should get zero bind device admin target users as
3781 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003783 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3784 MoreAsserts.assertEmpty(targetUsers);
3785
3786 // Calling from managed profile admin, we should still get zero target users for the same
3787 // reason.
3788 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3789 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3790 MoreAsserts.assertEmpty(targetUsers);
3791 }
3792
Jason Parks3c13b642017-11-28 15:39:43 -06003793 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003794 verifyLockTaskState(userId, new String[0],
3795 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003796 }
3797
3798 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3799 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003800 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003801 }
3802
3803 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3804 int flags) throws Exception {
3805 mContext.binder.callingUid = uid;
3806 dpm.setLockTaskPackages(who, packages);
3807 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3808 for (String p : packages) {
3809 assertTrue(dpm.isLockTaskPermitted(p));
3810 }
3811 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3812 // Test to see if set lock task features can be set
3813 dpm.setLockTaskFeatures(who, flags);
3814 verifyLockTaskState(userId, packages, flags);
3815 }
3816
3817 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3818 int flags) throws Exception {
3819 mContext.binder.callingUid = uid;
3820 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3821 () -> dpm.setLockTaskPackages(who, packages));
3822 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3823 () -> dpm.getLockTaskPackages(who));
3824 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3825 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3826 () -> dpm.setLockTaskFeatures(who, flags));
3827 }
3828
Charles Hee078db72017-10-19 18:03:20 +01003829 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003830 // Setup a device owner.
3831 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3832 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003833 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003834 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003835
3836 // Set up a managed profile managed by different package (package name shouldn't matter)
3837 final int MANAGED_PROFILE_USER_ID = 15;
3838 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3839 final ComponentName adminDifferentPackage =
3840 new ComponentName("another.package", "whatever.class");
3841 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003842 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3843
3844 // Setup a PO on the secondary user
3845 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3846 setAsProfileOwner(admin3);
3847 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003848
3849 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003850 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003851 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003852 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3853 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003854 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3855
3856 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3857 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003858 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3859 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003860 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003861
3862 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3863 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3864 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003865 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003866 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3867 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003868 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003869
3870 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003871 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003872 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3873 dpm.setAffiliationIds(admin1, userAffiliationIds);
3874
3875 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3876 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3877
3878 // Now the managed profile can set lock task packages.
3879 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3880 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3881 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3882 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003883 // And it can set lock task features.
3884 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003885 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003886
3887 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003888 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003889 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3890 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003891 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3892 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003893 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003894 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003895
Jason Parks3c13b642017-11-28 15:39:43 -06003896 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003897 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3898 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003899
3900 }
3901
3902 public void testLockTaskPolicyForProfileOwner() throws Exception {
3903 // Setup a PO
3904 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3905 setAsProfileOwner(admin1);
3906 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3907
3908 final String[] poPackages = {"poPackage1", "poPackage2"};
3909 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003910 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3911 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003912 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3913 poPackages, poFlags);
3914
3915 // Set up a managed profile managed by different package (package name shouldn't matter)
3916 final int MANAGED_PROFILE_USER_ID = 15;
3917 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3918 final ComponentName adminDifferentPackage =
3919 new ComponentName("another.package", "whatever.class");
3920 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3921 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3922
3923 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3924 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3925 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3926 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003927 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3928 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003929 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003930 }
3931
Benjamin Franzcaffa772018-02-05 16:36:10 +00003932 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3933 // Setup a device owner.
3934 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3935 setupDeviceOwner();
3936 // Lock task policy is updated when loading user data.
3937 verifyLockTaskState(UserHandle.USER_SYSTEM);
3938
3939 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3940 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3941 assertExpectException(IllegalArgumentException.class,
3942 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3943 () -> dpm.setLockTaskFeatures(admin1, flags));
3944 }
3945
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003946 public void testIsDeviceManaged() throws Exception {
3947 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3948 setupDeviceOwner();
3949
3950 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3951 // find out that the device has a device owner.
3952 assertTrue(dpm.isDeviceManaged());
3953 mContext.binder.callingUid = 1234567;
3954 mContext.callerPermissions.add(permission.MANAGE_USERS);
3955 assertTrue(dpm.isDeviceManaged());
3956 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3957 mContext.binder.clearCallingIdentity();
3958 assertTrue(dpm.isDeviceManaged());
3959
3960 clearDeviceOwner();
3961
3962 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3963 // not have a device owner.
3964 mContext.binder.callingUid = 1234567;
3965 mContext.callerPermissions.add(permission.MANAGE_USERS);
3966 assertFalse(dpm.isDeviceManaged());
3967 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3968 mContext.binder.clearCallingIdentity();
3969 assertFalse(dpm.isDeviceManaged());
3970 }
3971
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003972 public void testDeviceOwnerOrganizationName() throws Exception {
3973 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3974 setupDeviceOwner();
3975
3976 dpm.setOrganizationName(admin1, "organization");
3977
3978 // Device owner can retrieve organization managing the device.
3979 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3980
3981 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3982 mContext.binder.callingUid = 1234567;
3983 mContext.callerPermissions.add(permission.MANAGE_USERS);
3984 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3985 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3986
3987 // System can retrieve organization managing the device.
3988 mContext.binder.clearCallingIdentity();
3989 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3990
3991 // Removing the device owner clears the organization managing the device.
3992 clearDeviceOwner();
3993 assertNull(dpm.getDeviceOwnerOrganizationName());
3994 }
3995
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003996 public void testWipeDataManagedProfile() throws Exception {
3997 final int MANAGED_PROFILE_USER_ID = 15;
3998 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3999 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4000 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4001
4002 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004003 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004004 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004005 // Get mock reason string since we throw an IAE with empty string input.
4006 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4007 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004008
4009 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004010 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004011 MANAGED_PROFILE_USER_ID);
4012 }
4013
4014 public void testWipeDataManagedProfileDisallowed() throws Exception {
4015 final int MANAGED_PROFILE_USER_ID = 15;
4016 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4017 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4018
4019 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004020 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004021 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4022
Pavel Grafov75c0a892017-05-18 17:28:27 +01004023 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004024 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4025 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4026 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004027 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4028 thenReturn("Just a test string.");
4029
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004030 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004031 // The PO is not allowed to remove the profile if the user restriction was set on the
4032 // profile by the system
4033 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4034 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004035 }
4036
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004037 public void testWipeDataDeviceOwner() throws Exception {
4038 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004039 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004040 UserManager.DISALLOW_FACTORY_RESET,
4041 UserHandle.SYSTEM))
4042 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004043 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4044 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004045
4046 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004047 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004048 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4049 /*wipeEuicc=*/ eq(false));
4050 }
4051
4052 public void testWipeEuiccDataEnabled() throws Exception {
4053 setDeviceOwner();
4054 when(getServices().userManager.getUserRestrictionSource(
4055 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.");
yinxuf4f9cec2017-06-19 10:28:19 -07004060
4061 dpm.wipeData(WIPE_EUICC);
4062 verify(getServices().recoverySystem).rebootWipeUserData(
4063 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4064 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004065 }
4066
4067 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4068 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004069 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004070 UserManager.DISALLOW_FACTORY_RESET,
4071 UserHandle.SYSTEM))
4072 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
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.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004075 // The DO is not allowed to wipe the device if the user restriction was set
4076 // by the system
4077 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4078 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004079 }
4080
4081 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4082 final int MANAGED_PROFILE_USER_ID = 15;
4083 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4084 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4085
4086 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004087 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004088 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4089
Pavel Grafov75c0a892017-05-18 17:28:27 +01004090 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004091 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4092 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4093 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4094
4095 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4096 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4097
4098 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4099 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4100 // Failed password attempts on the parent user are taken into account, as there isn't a
4101 // separate work challenge.
4102 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4103 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4104 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4105
4106 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4107 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004108 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004109 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004110 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004111 }
4112
4113 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4114 throws Exception {
4115 final int MANAGED_PROFILE_USER_ID = 15;
4116 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4117 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4118
4119 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004120 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004121 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4122
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004124 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4125 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4126 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4127
4128 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4129 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4130
4131 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4132 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4133 // Failed password attempts on the parent user are taken into account, as there isn't a
4134 // separate work challenge.
4135 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4136 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4137 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4138
4139 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4140 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004141 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004142 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004143 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004144 }
4145
4146 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4147 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004148 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004149 UserManager.DISALLOW_FACTORY_RESET,
4150 UserHandle.SYSTEM))
4151 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4152
4153 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4154
4155 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4156 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4157 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4158 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4159 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4160
4161 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4162 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004163 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004164 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4165 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004166 }
4167
4168 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4169 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004170 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004171 UserManager.DISALLOW_FACTORY_RESET,
4172 UserHandle.SYSTEM))
4173 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4174
4175 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4176
4177 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4178 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4179 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4180 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4181 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4182
4183 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004184 verifyZeroInteractions(getServices().recoverySystem);
4185 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004186 .removeUserEvenWhenDisallowed(anyInt());
4187 }
4188
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004189 public void testGetPermissionGrantState() throws Exception {
4190 final String permission = "some.permission";
4191 final String app1 = "com.example.app1";
4192 final String app2 = "com.example.app2";
4193
Pavel Grafov75c0a892017-05-18 17:28:27 +01004194 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004195 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004196 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004197 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004198 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004199 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4200 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004201 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004202 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004203 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004204 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004205 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004206 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4207
4208 // System can retrieve permission grant state.
4209 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004210 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004211 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4212 dpm.getPermissionGrantState(null, app1, permission));
4213 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4214 dpm.getPermissionGrantState(null, app2, permission));
4215
4216 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004217 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4218 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004219 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4220 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004221
4222 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004223 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4224 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004225 setAsProfileOwner(admin1);
4226 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4227 dpm.getPermissionGrantState(admin1, app1, permission));
4228 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4229 dpm.getPermissionGrantState(admin1, app2, permission));
4230 }
4231
Rubin Xuaab7a412016-12-30 21:13:29 +00004232 public void testResetPasswordWithToken() throws Exception {
4233 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4234 setupDeviceOwner();
4235 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004236 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4237 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4238
Rubin Xuaab7a412016-12-30 21:13:29 +00004239 // test adding a token
4240 final byte[] token = new byte[32];
4241 final long handle = 123456;
4242 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004243 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4244 nullable(EscrowTokenStateChangeCallback.class)))
4245 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004246 assertTrue(dpm.setResetPasswordToken(admin1, token));
4247
4248 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004249 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004250 .thenReturn(true);
4251 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4252
4253 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004254 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4255 eq(LockscreenCredential.createPassword(password)),
4256 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004257 eq(UserHandle.USER_SYSTEM)))
4258 .thenReturn(true);
4259 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4260
4261 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004262 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004263 .thenReturn(true);
4264 assertTrue(dpm.clearResetPasswordToken(admin1));
4265 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004266
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004267 public void testIsActivePasswordSufficient() throws Exception {
4268 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4269 mContext.packageName = admin1.getPackageName();
4270 setupDeviceOwner();
4271
4272 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4273 dpm.setPasswordMinimumLength(admin1, 8);
4274 dpm.setPasswordMinimumLetters(admin1, 6);
4275 dpm.setPasswordMinimumLowerCase(admin1, 3);
4276 dpm.setPasswordMinimumUpperCase(admin1, 1);
4277 dpm.setPasswordMinimumNonLetter(admin1, 1);
4278 dpm.setPasswordMinimumNumeric(admin1, 1);
4279 dpm.setPasswordMinimumSymbols(admin1, 0);
4280
Rubin Xucc391c22018-01-02 20:37:35 +00004281 reset(mContext.spiedContext);
4282
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004283 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4284 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4285 8, 2,
4286 6, 1,
4287 0, 1);
4288
4289 setActivePasswordState(passwordMetricsNoSymbols);
4290 assertTrue(dpm.isActivePasswordSufficient());
4291
4292 initializeDpms();
4293 reset(mContext.spiedContext);
4294 assertTrue(dpm.isActivePasswordSufficient());
4295
4296 // This call simulates the user entering the password for the first time after a reboot.
4297 // This causes password metrics to be reloaded into memory. Until this happens,
4298 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4299 // even if the DPC changes password requirements so that the password no longer meets the
4300 // requirements. This is a known limitation of the current implementation of
4301 // isActivePasswordSufficient() - see b/34218769.
4302 setActivePasswordState(passwordMetricsNoSymbols);
4303 assertTrue(dpm.isActivePasswordSufficient());
4304
4305 dpm.setPasswordMinimumSymbols(admin1, 1);
4306 // This assertion would fail if we had not called setActivePasswordState() again after
4307 // initializeDpms() - see previous comment.
4308 assertFalse(dpm.isActivePasswordSufficient());
4309
4310 initializeDpms();
4311 reset(mContext.spiedContext);
4312 assertFalse(dpm.isActivePasswordSufficient());
4313
4314 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4315 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4316 7, 2,
4317 5, 1,
4318 1, 2);
4319
4320 setActivePasswordState(passwordMetricsWithSymbols);
4321 assertTrue(dpm.isActivePasswordSufficient());
4322 }
4323
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004324 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4325 // If there is no lock screen, the password is considered empty no matter what, because
4326 // it provides no security.
4327 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4328
4329 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4330 mContext.packageName = admin1.getPackageName();
4331 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004332 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4333 // When there is no lockscreen, user password metrics is always empty.
4334 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4335 .thenReturn(new PasswordMetrics());
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004336
4337 // If no password requirements are set, isActivePasswordSufficient should succeed.
4338 assertTrue(dpm.isActivePasswordSufficient());
4339
4340 // Now set some password quality requirements.
4341 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4342
4343 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004344 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004345 dpm.reportPasswordChanged(userHandle);
4346
4347 // No broadcast should be sent.
4348 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4349 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4350 MockUtils.checkUserHandle(userHandle));
4351
4352 // The active (nonexistent) password doesn't comply with the requirements.
4353 assertFalse(dpm.isActivePasswordSufficient());
4354 }
4355
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4357 throws Exception {
4358 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004359 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004360
Rubin Xu19854862019-08-15 16:37:23 +01004361 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4362 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004363 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004364
Rubin Xucc391c22018-01-02 20:37:35 +00004365 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4366 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004367 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004368 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4369 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004370 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004371 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4372 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004373 // userId, if the password checkpoint value changes.
4374 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4375 MockUtils.checkIntentAction(
4376 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4377 MockUtils.checkUserHandle(userHandle));
4378 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004379 MockUtils.checkIntentAction(
4380 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4381 MockUtils.checkUserHandle(userHandle));
4382
Pavel Grafov75c0a892017-05-18 17:28:27 +01004383 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4384 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004385 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004386
4387 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4388 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004389 MockUtils.checkUserHandle(userHandle),
4390 eq(null),
4391 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004392
4393 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4394 // let it finish with system uid, otherwise it will throw and crash.
4395 flushTasks();
4396
4397 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004398 }
4399
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004400 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4401 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4402 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4403 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4404 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4405 DpmMockContext.SYSTEM_UID);
4406 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4407 DpmMockContext.SYSTEM_UID);
4408
4409 // Set up a device owner.
4410 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004411 setupDeviceOwner();
4412
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004413 // First and second user set IMEs manually.
4414 mContext.binder.callingUid = firstUserSystemUid;
4415 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4416 mContext.binder.callingUid = secondUserSystemUid;
4417 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004418
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004419 // Device owner changes IME for first user.
4420 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004421 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004422 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004423 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004424 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004425 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004426 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004427 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4428 mContext.binder.callingUid = firstUserSystemUid;
4429 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4430 mContext.binder.callingUid = secondUserSystemUid;
4431 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004432
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004433 // Second user changes IME manually.
4434 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4435 mContext.binder.callingUid = firstUserSystemUid;
4436 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4437 mContext.binder.callingUid = secondUserSystemUid;
4438 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004439
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004440 // First user changes IME manually.
4441 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4442 mContext.binder.callingUid = firstUserSystemUid;
4443 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4444 mContext.binder.callingUid = secondUserSystemUid;
4445 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004446
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004447 // Device owner changes IME for first user again.
4448 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004449 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004450 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004451 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004452 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004453 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004454 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4455 mContext.binder.callingUid = firstUserSystemUid;
4456 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4457 mContext.binder.callingUid = secondUserSystemUid;
4458 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459
4460 // Restarting the DPMS should not lose information.
4461 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004462 mContext.binder.callingUid = firstUserSystemUid;
4463 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4464 mContext.binder.callingUid = secondUserSystemUid;
4465 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004466
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004467 // Device owner can find out whether it set the current IME itself.
4468 mContext.binder.callingUid = deviceOwnerUid;
4469 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004470
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004471 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004472 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004473 mContext.binder.callingUid = firstUserSystemUid;
4474 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4475 mContext.binder.callingUid = secondUserSystemUid;
4476 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004477 }
4478
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004479 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4480 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4481 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4482 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4483 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4484 DpmMockContext.SYSTEM_UID);
4485 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4486 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004487
4488 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004489 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004490 setupProfileOwner();
4491
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004492 // First and second user set IMEs manually.
4493 mContext.binder.callingUid = firstUserSystemUid;
4494 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4495 mContext.binder.callingUid = secondUserSystemUid;
4496 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004497
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004498 // Profile owner changes IME for second user.
4499 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004500 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004501 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004502 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004503 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004504 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004505 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004506 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4507 mContext.binder.callingUid = firstUserSystemUid;
4508 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4509 mContext.binder.callingUid = secondUserSystemUid;
4510 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004511
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004512 // First user changes IME manually.
4513 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4514 mContext.binder.callingUid = firstUserSystemUid;
4515 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4516 mContext.binder.callingUid = secondUserSystemUid;
4517 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004518
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004519 // Second user changes IME manually.
4520 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4521 mContext.binder.callingUid = firstUserSystemUid;
4522 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4523 mContext.binder.callingUid = secondUserSystemUid;
4524 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004525
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004526 // Profile owner changes IME for second user again.
4527 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004528 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004529 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004530 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004531 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004532 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004533 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4534 mContext.binder.callingUid = firstUserSystemUid;
4535 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4536 mContext.binder.callingUid = secondUserSystemUid;
4537 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004538
4539 // Restarting the DPMS should not lose information.
4540 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004541 mContext.binder.callingUid = firstUserSystemUid;
4542 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4543 mContext.binder.callingUid = secondUserSystemUid;
4544 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004545
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004546 // Profile owner can find out whether it set the current IME itself.
4547 mContext.binder.callingUid = profileOwnerUid;
4548 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004549
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004550 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004551 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004552 mContext.binder.callingUid = firstUserSystemUid;
4553 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4554 mContext.binder.callingUid = secondUserSystemUid;
4555 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004556 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004557
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004558 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4559 throws Exception {
4560 // Set up a device owner.
4561 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4562 setupDeviceOwner();
4563 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4564 }
4565
4566 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4567 throws Exception {
4568 // Set up a profile owner.
4569 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4570 setupProfileOwner();
4571 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4572 }
4573
4574 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4575 int adminUid) throws Exception {
4576 mContext.binder.callingUid = adminUid;
4577 final int userId = UserHandle.getUserId(adminUid);
4578
4579 final String packageName = "some.package";
4580 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4581 admin1, Collections.singletonList(packageName)));
4582 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4583
4584 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4585 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4586
4587 // Attempt to set to empty list (which means no listener is whitelisted)
4588 mContext.binder.callingUid = adminUid;
4589 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004590 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004591 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4592
4593 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4594 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4595 }
4596
4597 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4598 // Set up a managed profile
4599 final int MANAGED_PROFILE_USER_ID = 15;
4600 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4601 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4602 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4603
4604 final String permittedListener = "some.package";
4605 setupPackageInPackageManager(
4606 permittedListener,
4607 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4608 /*appId=*/ 12345, /*flags=*/ 0);
4609
4610 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4611 admin1, Collections.singletonList(permittedListener)));
4612
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004613 // isNotificationListenerServicePermitted should throw if not called from System.
4614 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4615 () -> dpms.isNotificationListenerServicePermitted(
4616 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004617
4618 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4619 assertTrue(dpms.isNotificationListenerServicePermitted(
4620 permittedListener, MANAGED_PROFILE_USER_ID));
4621 }
4622
4623 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4624 throws Exception {
4625 // Set up a managed profile
4626 final int MANAGED_PROFILE_USER_ID = 15;
4627 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4628 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4629 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4630
4631 final String permittedListener = "permitted.package";
4632 int appId = 12345;
4633 setupPackageInPackageManager(
4634 permittedListener,
4635 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4636 appId, /*flags=*/ 0);
4637
4638 final String notPermittedListener = "not.permitted.package";
4639 setupPackageInPackageManager(
4640 notPermittedListener,
4641 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4642 ++appId, /*flags=*/ 0);
4643
4644 final String systemListener = "system.package";
4645 setupPackageInPackageManager(
4646 systemListener,
4647 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4648 ++appId, ApplicationInfo.FLAG_SYSTEM);
4649
4650 // By default all packages are allowed
4651 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4652
4653 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4654 assertTrue(dpms.isNotificationListenerServicePermitted(
4655 permittedListener, MANAGED_PROFILE_USER_ID));
4656 assertTrue(dpms.isNotificationListenerServicePermitted(
4657 notPermittedListener, MANAGED_PROFILE_USER_ID));
4658 assertTrue(dpms.isNotificationListenerServicePermitted(
4659 systemListener, MANAGED_PROFILE_USER_ID));
4660
4661 // Setting only one package in the whitelist
4662 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4663 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4664 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004665 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004666 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4667 assertEquals(1, permittedListeners.size());
4668 assertEquals(permittedListener, permittedListeners.get(0));
4669
4670 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4671 assertTrue(dpms.isNotificationListenerServicePermitted(
4672 permittedListener, MANAGED_PROFILE_USER_ID));
4673 assertFalse(dpms.isNotificationListenerServicePermitted(
4674 notPermittedListener, MANAGED_PROFILE_USER_ID));
4675 // System packages are always allowed (even if not in the whitelist)
4676 assertTrue(dpms.isNotificationListenerServicePermitted(
4677 systemListener, MANAGED_PROFILE_USER_ID));
4678
4679 // Setting an empty whitelist - only system listeners allowed
4680 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4681 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004682 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004683 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4684
4685 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4686 assertFalse(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 a null whitelist - all listeners allowed
4695 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4696 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4697 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4698
4699 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4700 assertTrue(dpms.isNotificationListenerServicePermitted(
4701 permittedListener, MANAGED_PROFILE_USER_ID));
4702 assertTrue(dpms.isNotificationListenerServicePermitted(
4703 notPermittedListener, MANAGED_PROFILE_USER_ID));
4704 assertTrue(dpms.isNotificationListenerServicePermitted(
4705 systemListener, MANAGED_PROFILE_USER_ID));
4706 }
4707
4708 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4709 throws Exception {
4710 // Set up a managed profile
4711 final int MANAGED_PROFILE_USER_ID = 15;
4712 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4713 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4714 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4715
4716 final String nonSystemPackage = "non.system.package";
4717 int appId = 12345;
4718 setupPackageInPackageManager(
4719 nonSystemPackage,
4720 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4721 appId, /*flags=*/ 0);
4722
4723 final String systemListener = "system.package";
4724 setupPackageInPackageManager(
4725 systemListener,
4726 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4727 ++appId, ApplicationInfo.FLAG_SYSTEM);
4728
4729 // By default all packages are allowed (for all profiles)
4730 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4731
4732 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4733 assertTrue(dpms.isNotificationListenerServicePermitted(
4734 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4735 assertTrue(dpms.isNotificationListenerServicePermitted(
4736 systemListener, MANAGED_PROFILE_USER_ID));
4737 assertTrue(dpms.isNotificationListenerServicePermitted(
4738 nonSystemPackage, UserHandle.USER_SYSTEM));
4739 assertTrue(dpms.isNotificationListenerServicePermitted(
4740 systemListener, UserHandle.USER_SYSTEM));
4741
4742 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4743 // all allowed in primary profile
4744 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4745 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004746 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004747 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4748
4749 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4750 assertFalse(dpms.isNotificationListenerServicePermitted(
4751 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4752 assertTrue(dpms.isNotificationListenerServicePermitted(
4753 systemListener, MANAGED_PROFILE_USER_ID));
4754 assertTrue(dpms.isNotificationListenerServicePermitted(
4755 nonSystemPackage, UserHandle.USER_SYSTEM));
4756 assertTrue(dpms.isNotificationListenerServicePermitted(
4757 systemListener, UserHandle.USER_SYSTEM));
4758 }
4759
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004760 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004761 mServiceContext.packageName = mRealTestContext.getPackageName();
4762 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4763 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004764 setDeviceOwner();
4765
Pavel Grafov75c0a892017-05-18 17:28:27 +01004766 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004767 }
4768
4769 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004770 mServiceContext.packageName = mRealTestContext.getPackageName();
4771 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4772 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004773 setAsProfileOwner(admin1);
4774
Pavel Grafov75c0a892017-05-18 17:28:27 +01004775 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4776 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004777 }
4778
4779 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004780 mServiceContext.packageName = mRealTestContext.getPackageName();
4781 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4782 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004783 setAsProfileOwner(admin1);
4784
Pavel Grafov75c0a892017-05-18 17:28:27 +01004785 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4786 caller.packageName = "com.example.delegate";
4787 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4788 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004789
Pavel Grafov75c0a892017-05-18 17:28:27 +01004790 // Make caller a delegated cert installer.
4791 runAsCaller(mAdmin1Context, dpms,
4792 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004793
4794 verifyCanGetOwnerInstalledCaCerts(null, caller);
4795 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004796 }
4797
Rubin Xucc391c22018-01-02 20:37:35 +00004798 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004799 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4800 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004801 Bundle restriction = new Bundle();
4802 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4803
4804 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4805 RestrictionsListener listener = new RestrictionsListener(mContext);
4806 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4807 new Bundle());
4808 verifyDataSharingChangedBroadcast();
4809 }
4810
4811 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004812 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4813 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004814 Bundle restriction = new Bundle();
4815 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4816
4817 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4818 RestrictionsListener listener = new RestrictionsListener(mContext);
4819 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4820 restriction);
4821 verifyDataSharingChangedBroadcast();
4822 }
4823
4824 public void testDisallowSharingIntoProfileUnchanged() {
4825 RestrictionsListener listener = new RestrictionsListener(mContext);
4826 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4827 new Bundle());
4828 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4829 }
4830
4831 private void verifyDataSharingChangedBroadcast() {
4832 Intent expectedIntent = new Intent(
4833 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4834 expectedIntent.setPackage("com.android.managedprovisioning");
4835 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4836 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4837 MockUtils.checkIntent(expectedIntent),
4838 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4839 }
4840
yuemingwe3d9c092018-01-11 12:11:44 +00004841 public void testOverrideApnAPIsFailWithPO() throws Exception {
4842 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004843 ApnSetting apn = (new ApnSetting.Builder())
4844 .setApnName("test")
4845 .setEntryName("test")
4846 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4847 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004848 assertExpectException(SecurityException.class, null, () ->
4849 dpm.addOverrideApn(admin1, apn));
4850 assertExpectException(SecurityException.class, null, () ->
4851 dpm.updateOverrideApn(admin1, 0, apn));
4852 assertExpectException(SecurityException.class, null, () ->
4853 dpm.removeOverrideApn(admin1, 0));
4854 assertExpectException(SecurityException.class, null, () ->
4855 dpm.getOverrideApns(admin1));
4856 assertExpectException(SecurityException.class, null, () ->
4857 dpm.setOverrideApnsEnabled(admin1, false));
4858 assertExpectException(SecurityException.class, null, () ->
4859 dpm.isOverrideApnEnabled(admin1));
4860 }
4861
Robin Lee2c68dad2017-03-17 12:50:24 +00004862 private void verifyCanGetOwnerInstalledCaCerts(
4863 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004864 final String alias = "cert";
4865 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004866
4867 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004868 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004869 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4870 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004871 }
4872 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4873
4874 // caller: device admin or delegated certificate installer
4875 callerContext.applicationInfo = new ApplicationInfo();
4876 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4877
4878 // system_server
4879 final DpmMockContext serviceContext = mContext;
4880 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004881 getServices().addPackageContext(callerUser, admin1Context);
4882 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004883
4884 // Install a CA cert.
4885 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004886 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004887 .thenReturn(alias);
4888 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004889 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004890 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004891 });
4892
Pavel Grafov75c0a892017-05-18 17:28:27 +01004893 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4894 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4895 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004896 flushTasks();
4897
Robin Lee2c68dad2017-03-17 12:50:24 +00004898 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4899
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004900 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004901 runAsCaller(admin1Context, dpms, (dpm) -> {
4902 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004903 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004904 ownerInstalledCaCerts.addAll(installedCaCerts);
4905 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004906
4907 // Restarting the DPMS should not lose information.
4908 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004909 runAsCaller(admin1Context, dpms, (dpm) ->
4910 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004911
4912 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004913 runAsCaller(serviceContext, dpms, (dpm) -> {
4914 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004915
Robin Lee2c68dad2017-03-17 12:50:24 +00004916 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004917 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004918 });
4919
Pavel Grafov75c0a892017-05-18 17:28:27 +01004920 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4921 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4922 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004923 flushTasks();
4924
4925 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4926 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004927 runAsCaller(admin1Context, dpms, (dpm) -> {
4928 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4929 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004930 }
4931
Robin Lee2c68dad2017-03-17 12:50:24 +00004932 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4933 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004934 final String alias = "cert";
4935 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004936
4937 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004938 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004939 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4940 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004941 }
4942 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4943
4944 // caller: device admin or delegated certificate installer
4945 callerContext.applicationInfo = new ApplicationInfo();
4946 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4947
4948 // system_server
4949 final DpmMockContext serviceContext = mContext;
4950 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004951 getServices().addPackageContext(callerUser, admin1Context);
4952 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004953
4954 // Install a CA cert as caller
4955 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004956 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004957 .thenReturn(alias);
4958 assertTrue(dpm.installCaCert(callerName, caCert));
4959 });
4960
4961 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004962 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004963 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004964 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4965 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4966 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004967 flushTasks();
4968
Robin Lee2c68dad2017-03-17 12:50:24 +00004969 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004970 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004971
4972 runAsCaller(serviceContext, dpms, (dpm) -> {
4973 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4974 assertNotNull(ownerInstalledCaCerts);
4975 assertTrue(ownerInstalledCaCerts.isEmpty());
4976 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004977 }
4978
Eran Messeri94d56762017-12-21 20:50:54 +00004979 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4980 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4981 Arrays.sort(gotFlags);
4982 Arrays.sort(expectedFlags);
4983 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4984 }
4985
4986 public void testTranslationOfIdAttestationFlag() {
4987 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4988 int[] correspondingAttUtilsTypes = new int[]{
4989 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4990 AttestationUtils.ID_TYPE_MEID};
4991
4992 // Test translation of zero flags
4993 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4994
4995 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4996 // non-null array
4997 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4998
4999 // Test translation of a single flag
5000 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5001 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5002 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5003
5004 // Test translation of two flags
5005 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5006 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5007 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5008 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5009
5010 // Test translation of all three flags
5011 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5012 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5013 AttestationUtils.ID_TYPE_MEID});
5014 // Test translation of all three flags
5015 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5016 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5017 AttestationUtils.ID_TYPE_MEID});
5018 }
5019
arangelov08d534b2018-01-22 15:20:53 +00005020 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5021 setDeviceOwner();
5022 initializeDpms();
5023 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5024 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5025 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5026 }
5027
5028 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5029 DpmTestUtils.writeInputStreamToFile(
5030 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5031 getDeviceOwnerPoliciesFile());
5032 DpmTestUtils.writeInputStreamToFile(
5033 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5034 getDeviceOwnerFile());
5035 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5036 }
5037
5038 public void testRevertDeviceOwnership_deviceNotMigrated()
5039 throws Exception {
5040 DpmTestUtils.writeInputStreamToFile(
5041 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5042 getDeviceOwnerPoliciesFile());
5043 DpmTestUtils.writeInputStreamToFile(
5044 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5045 getDeviceOwnerFile());
5046 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5047 }
5048
5049 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5050 throws Exception {
5051 DpmTestUtils.writeInputStreamToFile(
5052 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5053 getDeviceOwnerPoliciesFile());
5054 DpmTestUtils.writeInputStreamToFile(
5055 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5056 getDeviceOwnerFile());
5057 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5058 }
5059
5060 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5061 setupProfileOwner();
5062 initializeDpms();
5063 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5064 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5065 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5066 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5067 }
5068
5069 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5070 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5071 UserHandle.USER_SYSTEM);
5072 DpmTestUtils.writeInputStreamToFile(
5073 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5074 getProfileOwnerPoliciesFile());
5075 DpmTestUtils.writeInputStreamToFile(
5076 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5077 getProfileOwnerFile());
5078 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5079 }
5080
5081 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5082 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5083 UserHandle.USER_SYSTEM);
5084 DpmTestUtils.writeInputStreamToFile(
5085 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5086 getProfileOwnerPoliciesFile());
5087 DpmTestUtils.writeInputStreamToFile(
5088 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5089 getProfileOwnerFile());
5090 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5091 }
5092
5093 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5094 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5095 UserHandle.USER_SYSTEM);
5096 DpmTestUtils.writeInputStreamToFile(
5097 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5098 getProfileOwnerPoliciesFile());
5099 DpmTestUtils.writeInputStreamToFile(
5100 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5101 getProfileOwnerFile());
5102 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5103 }
5104
Eran Messeribb271892018-10-17 18:27:50 +01005105 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5106 setupProfileOwner();
5107 configureContextForAccess(mContext, false);
5108
5109 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005110 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005111 }
5112
5113 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5114 setupProfileOwner();
5115 configureContextForAccess(mContext, false);
5116
5117 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005118 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005119 }
5120
5121 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5122 setupProfileOwner();
5123
5124 // This method will throw if the system context could not call
5125 // setProfileOwnerCanAccessDeviceIds successfully.
5126 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5127 }
5128
5129 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5130 when(context.spiedContext.checkCallingPermission(
5131 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5132 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5133 : PackageManager.PERMISSION_DENIED);
5134 }
5135
5136 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5137 setupProfileOwner();
5138
5139 final long ident = mServiceContext.binder.clearCallingIdentity();
5140 configureContextForAccess(mServiceContext, true);
5141
5142 mServiceContext.binder.callingUid =
5143 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5144 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5145 try {
5146 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005147 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005148 });
5149 } finally {
5150 mServiceContext.binder.restoreCallingIdentity(ident);
5151 }
5152 }
5153
5154 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5155 throws Exception {
5156 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5157 setupDeviceOwner();
5158 configureContextForAccess(mContext, false);
5159
5160 // Device owner should be allowed to request Device ID attestation.
5161 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5162 DpmMockContext.CALLER_SYSTEM_USER_UID);
5163
5164 // Another package must not be allowed to request Device ID attestation.
5165 assertExpectException(SecurityException.class, null,
5166 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5167 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5168 // Another component that is not the admin must not be allowed to request Device ID
5169 // attestation.
5170 assertExpectException(SecurityException.class, null,
5171 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5172 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5173 }
5174
5175 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5176 throws Exception {
5177 configureContextForAccess(mContext, false);
5178
5179 // Make sure a security exception is thrown if the device has no profile owner.
5180 assertExpectException(SecurityException.class, null,
5181 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5182 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5183
5184 setupProfileOwner();
5185 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5186
5187 // The profile owner is allowed to request Device ID attestation.
5188 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5189 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5190 DpmMockContext.CALLER_UID);
5191 // But not another package.
5192 assertExpectException(SecurityException.class, null,
5193 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5194 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5195 // Or another component which is not the admin.
5196 assertExpectException(SecurityException.class, null,
5197 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5198 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5199 }
5200
5201 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5202 final long ident = mServiceContext.binder.clearCallingIdentity();
5203
5204 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5205 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5206 try {
5207 runAsCaller(mServiceContext, dpms, action);
5208 } finally {
5209 mServiceContext.binder.restoreCallingIdentity(ident);
5210 }
5211 }
5212
5213 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5214 setupProfileOwner();
5215 markDelegatedCertInstallerAsInstalled();
5216
5217 // Configure a delegated cert installer.
5218 runAsCaller(mServiceContext, dpms,
5219 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5220 Arrays.asList(DELEGATION_CERT_INSTALL)));
5221
5222 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5223
5224 // Make sure that the profile owner can still request Device ID attestation.
5225 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5226 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5227 DpmMockContext.CALLER_UID);
5228
5229 runAsDelegatedCertInstaller(dpm -> {
5230 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5231 DpmMockContext.DELEGATE_PACKAGE_NAME,
5232 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5233 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5234 });
5235 }
5236
5237 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5238 throws Exception {
5239 setupProfileOwner();
5240 markDelegatedCertInstallerAsInstalled();
5241
5242 // Configure a delegated cert installer.
5243 runAsCaller(mServiceContext, dpms,
5244 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5245 Arrays.asList(DELEGATION_CERT_INSTALL)));
5246
5247
5248 assertExpectException(SecurityException.class, null,
5249 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5250 admin1.getPackageName(),
5251 DpmMockContext.CALLER_UID));
5252
5253 runAsDelegatedCertInstaller(dpm -> {
5254 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5255 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5256 DpmMockContext.DELEGATE_PACKAGE_NAME,
5257 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5258 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5259 });
5260 }
5261
Bernard Chaue9586552018-11-29 10:59:31 +00005262 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5263 assertThrows(SecurityException.class,
5264 () -> new DevicePolicyManagerTestable(
5265 mServiceContext,
5266 dpms,
5267 /* parentInstance= */ true)
5268 .getPasswordComplexity());
5269 }
5270
5271 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5272 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5273 .thenReturn(false);
5274 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5275 }
5276
5277 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5278 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5279 .thenReturn(true);
5280 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5281 }
5282
5283
5284 public void testGetPasswordComplexity_currentUserNoPassword() {
5285 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5286 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005287 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005288 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5289 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5290
5291 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5292 }
5293
5294 public void testGetPasswordComplexity_currentUserHasPassword() {
5295 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5296 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005297 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005298 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5299 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005300 when(getServices().lockSettingsInternal
5301 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5302 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005303
5304 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5305 }
5306
5307 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5308 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5309 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005310 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005311
5312 UserInfo parentUser = new UserInfo();
5313 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5314 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5315 .thenReturn(parentUser.id);
5316
Rubin Xu19854862019-08-15 16:37:23 +01005317 when(getServices().lockSettingsInternal
5318 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5319 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
5320 when(getServices().lockSettingsInternal
5321 .getUserPasswordMetrics(parentUser.id))
5322 .thenReturn(PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005323
5324 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5325 }
5326
yuemingwd2bfbc82019-01-02 11:42:25 +00005327 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5328 setAsProfileOwner(admin1);
5329 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5330 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5331 }
5332
5333 public void testCrossProfileCalendarPackages_reopenDpms() {
5334 setAsProfileOwner(admin1);
5335 dpm.setCrossProfileCalendarPackages(admin1, null);
5336 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5337 assertTrue(packages == null);
5338 initializeDpms();
5339 packages = dpm.getCrossProfileCalendarPackages(admin1);
5340 assertTrue(packages == null);
5341
5342 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5343 packages = dpm.getCrossProfileCalendarPackages(admin1);
5344 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5345 initializeDpms();
5346 packages = dpm.getCrossProfileCalendarPackages(admin1);
5347 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5348
5349 final String dummyPackageName = "test";
5350 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5351 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5352 packages = dpm.getCrossProfileCalendarPackages(admin1);
5353 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5354 initializeDpms();
5355 packages = dpm.getCrossProfileCalendarPackages(admin1);
5356 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5357 }
5358
5359 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5360 assertTrue(expected != null);
5361 assertTrue(actual != null);
5362 assertTrue(expected.containsAll(actual));
5363 assertTrue(actual.containsAll(expected));
5364 }
5365
yuemingwdded98f2019-01-30 17:08:12 +00005366 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5367 setAsProfileOwner(admin1);
5368 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5369 when(getServices().settings.settingsSecureGetIntForUser(
5370 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5371 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5372 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5373 }
5374
5375 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5376 final String testPackage = "TEST_PACKAGE";
5377 setAsProfileOwner(admin1);
5378 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5379 when(getServices().settings.settingsSecureGetIntForUser(
5380 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5381 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5382 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5383 }
5384
5385 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5386 final String testPackage = "TEST_PACKAGE";
5387 setAsProfileOwner(admin1);
5388 dpm.setCrossProfileCalendarPackages(admin1, null);
5389 when(getServices().settings.settingsSecureGetIntForUser(
5390 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5391 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5392 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5393 }
5394
Eran Messeribb271892018-10-17 18:27:50 +01005395 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5396 final long ident = mServiceContext.binder.clearCallingIdentity();
5397 mServiceContext.binder.callingUid =
5398 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5399 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005400 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005401 });
5402 mServiceContext.binder.restoreCallingIdentity(ident);
5403 }
5404
arangelov08d534b2018-01-22 15:20:53 +00005405 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5406 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5407 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5408 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5409
5410 final long ident = mServiceContext.binder.clearCallingIdentity();
5411 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5412 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5413 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5414 // To simulate a reboot, we just reinitialize dpms and call systemReady
5415 initializeDpms();
5416
5417 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5418 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5419 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5420 assertTrue(dpm.isAdminActive(admin1));
5421 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5422 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5423
5424 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5425 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5426 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5427 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5428
5429 mServiceContext.binder.restoreCallingIdentity(ident);
5430 }
5431
5432 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5433 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5434 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5435 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5436
5437 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5438 DpmMockContext.CALLER_SYSTEM_USER_UID);
5439 setUpPackageManagerForAdmin(admin1, uid);
5440 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5441 // To simulate a reboot, we just reinitialize dpms and call systemReady
5442 initializeDpms();
5443
5444 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5445 assertTrue(dpm.isAdminActive(admin1));
5446 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5447 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5448 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5449 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5450 }
5451
5452 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5453 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5454 metadataManager.deleteMetadataFile();
5455
5456 final TransferOwnershipMetadataManager.Metadata metadata =
5457 new TransferOwnershipMetadataManager.Metadata(
5458 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5459 callerUserHandle,
5460 adminType);
5461 metadataManager.saveMetadataFile(metadata);
5462 }
5463
5464 private File getDeviceOwnerFile() {
5465 return dpms.mOwners.getDeviceOwnerFile();
5466 }
5467
5468 private File getProfileOwnerFile() {
5469 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5470 }
5471
5472 private File getProfileOwnerPoliciesFile() {
5473 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5474 DpmMockContext.CALLER_USER_HANDLE);
5475 return getPoliciesFile(parentDir);
5476 }
5477
5478 private File getDeviceOwnerPoliciesFile() {
5479 return getPoliciesFile(getServices().systemUserDataDir);
5480 }
5481
5482 private File getPoliciesFile(File parentDir) {
5483 return new File(parentDir, "device_policies.xml");
5484 }
5485
5486 private InputStream getRawStream(@RawRes int id) {
5487 return mRealTestContext.getResources().openRawResource(id);
5488 }
5489
Victor Chang3e794af2016-03-04 13:48:17 +00005490 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005491 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005492 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5493 dpms.notifyChangeToContentObserver(
5494 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5495 }
5496
5497 private void assertProvisioningAllowed(String action, boolean expected) {
5498 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5499 dpm.isProvisioningAllowed(action));
5500 }
Tony Mak2f26b792016-11-28 17:54:51 +00005501
Nicolas Prevot45d29072017-01-18 16:11:19 +00005502 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5503 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005504 final String previousPackageName = mContext.packageName;
5505 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005506
5507 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5508 mContext.packageName = packageName;
5509 mMockContext.binder.callingUid = uid;
5510 assertProvisioningAllowed(action, expected);
5511
5512 // Set the previous package name / calling uid to go back to the initial state.
5513 mContext.packageName = previousPackageName;
5514 mMockContext.binder.callingUid = previousUid;
5515 }
5516
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005517 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005518 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5519 }
5520
5521 private void assertCheckProvisioningPreCondition(
5522 String action, String packageName, int provisioningCondition) {
5523 assertEquals("checkProvisioningPreCondition("
5524 + action + ", " + packageName + ") returning unexpected result",
5525 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005526 }
5527
Tony Mak2f26b792016-11-28 17:54:51 +00005528 /**
5529 * Setup a managed profile with the specified admin and its uid.
5530 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5531 * @param adminUid uid of the admin package.
5532 * @param copyFromAdmin package information for {@code admin} will be built based on this
5533 * component's information.
5534 */
5535 private void addManagedProfile(
5536 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5537 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005538 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005539 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5540 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5541 dpm.setActiveAdmin(admin, false, userId);
5542 assertTrue(dpm.setProfileOwner(admin, null, userId));
5543 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5544 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005545
5546 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005547 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005548 */
Robin Leeabaa0692017-02-20 20:54:22 +00005549 private static StringParceledListSlice asSlice(String[] s) {
5550 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005551 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005552
5553 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005554 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5555 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005556
Robin Lee2c68dad2017-03-17 12:50:24 +00005557 // We can't let exceptions happen on the background thread. Throw them here if they happen
5558 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005559 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005560 }
Victor Chang3e794af2016-03-04 13:48:17 +00005561}