blob: d6cb9826d51419a4798307641e4cb87493f3d5e7 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010028import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
29import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
30import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
31
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Pavel Grafov75c0a892017-05-18 17:28:27 +010035import static org.mockito.Matchers.any;
36import static org.mockito.Matchers.anyInt;
37import static org.mockito.Matchers.anyLong;
38import static org.mockito.Matchers.anyObject;
39import static org.mockito.Matchers.anyString;
40import static org.mockito.Matchers.eq;
41import static org.mockito.Matchers.isNull;
42import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010043import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010044import static org.mockito.Mockito.doAnswer;
45import static org.mockito.Mockito.doReturn;
46import static org.mockito.Mockito.never;
47import static org.mockito.Mockito.nullable;
48import static org.mockito.Mockito.reset;
49import static org.mockito.Mockito.timeout;
50import static org.mockito.Mockito.times;
51import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080052import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010053import static org.mockito.Mockito.verifyZeroInteractions;
54import static org.mockito.Mockito.when;
55import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000056import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010057
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000059import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010061import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000062import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063import android.app.admin.DeviceAdminReceiver;
64import android.app.admin.DevicePolicyManager;
65import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010066import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000069import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000070import android.content.pm.ApplicationInfo;
71import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010073import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000074import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000075import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010076import android.graphics.Color;
77import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080078import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070079import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080080import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070081import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070082import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010083import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080084import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010085import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000086import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000087import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000088import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080089import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010090import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092
Pavel Grafov57f1b662019-03-27 14:55:38 +000093import androidx.test.filters.SmallTest;
94
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010095import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000096import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000097import com.android.server.LocalServices;
98import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000099import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000100import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000101
Robin Lee7f5c91c2017-02-08 21:27:02 +0000102import org.hamcrest.BaseMatcher;
103import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800104import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700105import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106
arangelov08d534b2018-01-22 15:20:53 +0000107import java.io.File;
108import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800109import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000110import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000111import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700112import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700114import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100115import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000116import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700119 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000120 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 m FrameworksServicesTests &&
122 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000123 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700125 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126
127 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000128 *
129 * , or:
130 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000132@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100133@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000135 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
136 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
137 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100138 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800139 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100140 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000141
Pavel Grafov75c0a892017-05-18 17:28:27 +0100142 // TODO replace all instances of this with explicit {@link #mServiceContext}.
143 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700144 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100145
146 private DpmMockContext mServiceContext;
147 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700148 public DevicePolicyManager dpm;
149 public DevicePolicyManagerServiceTestable dpms;
150
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100151 /*
152 * The CA cert below is the content of cacert.pem as generated by:
153 *
154 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
155 */
156 private static final String TEST_CA =
157 "-----BEGIN CERTIFICATE-----\n" +
158 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
159 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
160 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
161 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
162 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
163 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
164 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
165 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
166 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
167 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
168 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
169 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
170 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
171 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
172 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
173 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
174 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
175 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
176 "wQ==\n" +
177 "-----END CERTIFICATE-----\n";
178
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700179 @Override
180 protected void setUp() throws Exception {
181 super.setUp();
182
183 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100184 mServiceContext = mContext;
185 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
186 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100188 doReturn(Collections.singletonList(new ResolveInfo()))
189 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
190 any(Intent.class),
191 anyInt(),
192 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700193
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800194 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800196
Makoto Onukia52562c2015-10-01 16:12:31 -0700197 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700198
Sudheer Shanka101c3532018-01-08 16:28:42 -0800199 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800200 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700201 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
202 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
203 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800204 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700205
Pavel Grafov75c0a892017-05-18 17:28:27 +0100206 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
207 mAdmin1Context.packageName = admin1.getPackageName();
208 mAdmin1Context.applicationInfo = new ApplicationInfo();
209 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
210
Makoto Onukib643fb02015-09-22 15:03:44 -0700211 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100212
213 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700214 }
215
arangelov08d534b2018-01-22 15:20:53 +0000216 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
217 return dpms.mTransferOwnershipMetadataManager;
218 }
219
Robin Lee2c68dad2017-03-17 12:50:24 +0000220 @Override
221 protected void tearDown() throws Exception {
222 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000223 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000224 super.tearDown();
225 }
226
Makoto Onukia52562c2015-10-01 16:12:31 -0700227 private void initializeDpms() {
228 // Need clearCallingIdentity() to pass permission checks.
229 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700231
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
233 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
234 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700239 }
240
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 private void setUpUserManager() {
242 // Emulate UserManager.set/getApplicationRestriction().
243 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
244
245 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000246 doAnswer((Answer<Void>) invocation -> {
247 String pkg = (String) invocation.getArguments()[0];
248 Bundle bundle = (Bundle) invocation.getArguments()[1];
249 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000251 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000253 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100255 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700256
257 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000258 doAnswer((Answer<Bundle>) invocation -> {
259 String pkg = (String) invocation.getArguments()[0];
260 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000262 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100263 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700264 anyString(), any(UserHandle.class));
265
Makoto Onukid932f762015-09-29 16:53:38 -0700266 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700268 }
269
270 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700272
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 mServiceContext.binder.callingUid =
274 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
275 runAsCaller(mServiceContext, dpms, dpm -> {
276 // PO needs to be a DA.
277 dpm.setActiveAdmin(admin, /*replace=*/ false);
278 // Fire!
279 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
280 // Check
281 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
282 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700283
Pavel Grafov75c0a892017-05-18 17:28:27 +0100284 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700285 }
286
287 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100288 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700289 .thenReturn(false);
290
291 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100292 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700293
294 // If the device has no DPMS feature, it shouldn't register the local service.
295 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
296 }
297
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800298 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800299 // Device owner in SYSTEM_USER
300 setDeviceOwner();
301 // Profile owner in CALLER_USER_HANDLE
302 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
303 setAsProfileOwner(admin2);
304 // Active admin in CALLER_USER_HANDLE
305 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
306 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
307 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
308 DpmMockContext.CALLER_USER_HANDLE);
309 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
310 DpmMockContext.CALLER_USER_HANDLE));
311
312 initializeDpms();
313
314 // Verify
315 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800316 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800317 eq(UserHandle.USER_SYSTEM));
318 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800319 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800320 adminAnotherPackage.getPackageName()),
321 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800322 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
323 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
324 }
325
326 public void testLoadAdminData_noAdmins() throws Exception {
327 final int ANOTHER_USER_ID = 15;
328 getServices().addUser(ANOTHER_USER_ID, 0);
329
330 initializeDpms();
331
332 // Verify
333 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
334 null, DpmMockContext.CALLER_USER_HANDLE);
335 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
336 null, ANOTHER_USER_ID);
337 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
338 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800339 }
340
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700341 /**
342 * Caller doesn't have proper permissions.
343 */
344 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700345 // 1. Failure cases.
346
347 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100348 assertExpectException(SecurityException.class, /* messageRegex= */ null,
349 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700350
351 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
352 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100353
354 assertExpectException(SecurityException.class, /* messageRegex= */ null,
355 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700356 }
357
Makoto Onukif76b06a2015-09-22 15:03:44 -0700358 /**
359 * Test for:
360 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800361 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362 * {@link DevicePolicyManager#isAdminActive}
363 * {@link DevicePolicyManager#isAdminActiveAsUser}
364 * {@link DevicePolicyManager#getActiveAdmins}
365 * {@link DevicePolicyManager#getActiveAdminsAsUser}
366 */
367 public void testSetActiveAdmin() throws Exception {
368 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700369 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
370
Makoto Onukif76b06a2015-09-22 15:03:44 -0700371 // 2. Call the API.
372 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373
374 // 3. Verify internal calls.
375
376 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700377 verify(mContext.spiedContext).sendBroadcastAsUser(
378 MockUtils.checkIntentAction(
379 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
380 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
381 verify(mContext.spiedContext).sendBroadcastAsUser(
382 MockUtils.checkIntentAction(
383 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100384 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
385 eq(null),
386 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700387
Pavel Grafov75c0a892017-05-18 17:28:27 +0100388 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389 eq(admin1.getPackageName()),
390 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
391 eq(PackageManager.DONT_KILL_APP),
392 eq(DpmMockContext.CALLER_USER_HANDLE),
393 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394
Sudheer Shanka101c3532018-01-08 16:28:42 -0800395 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
396 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
397
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700398 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700399
400 // Make sure it's active admin1.
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403 assertFalse(dpm.isAdminActive(admin3));
404
405 // But not admin1 for a different user.
406
407 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
408 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
409 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
412 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
413
414 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
415
416 // Next, add one more admin.
417 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700418 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700419 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700420
421 dpm.setActiveAdmin(admin2, /* replace =*/ false);
422
423 // Now we have two admins.
424 assertTrue(dpm.isAdminActive(admin1));
425 assertTrue(dpm.isAdminActive(admin2));
426 assertFalse(dpm.isAdminActive(admin3));
427
428 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
429 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100430 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431 eq(admin1.getPackageName()),
432 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
433 eq(PackageManager.DONT_KILL_APP),
434 eq(DpmMockContext.CALLER_USER_HANDLE),
435 anyString());
436
Sudheer Shanka101c3532018-01-08 16:28:42 -0800437 // times(2) because it was previously called for admin1 which is in the same package
438 // as admin2.
439 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
440 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
441
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100443 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
444 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445
446 // 5. Add the same admin1 again with replace, which should succeed.
447 dpm.setActiveAdmin(admin1, /* replace =*/ true);
448
449 // TODO make sure it's replaced.
450
451 // 6. Test getActiveAdmins()
452 List<ComponentName> admins = dpm.getActiveAdmins();
453 assertEquals(2, admins.size());
454 assertEquals(admin1, admins.get(0));
455 assertEquals(admin2, admins.get(1));
456
Sudheer Shanka101c3532018-01-08 16:28:42 -0800457 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
458 // replaced
459 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
460
Makoto Onukif76b06a2015-09-22 15:03:44 -0700461 // Another user has no admins.
462 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
463
464 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
465 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
466
467 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
468 }
469
Makoto Onukid932f762015-09-29 16:53:38 -0700470 public void testSetActiveAdmin_multiUsers() throws Exception {
471
472 final int ANOTHER_USER_ID = 100;
473 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
474
Pavel Grafov75c0a892017-05-18 17:28:27 +0100475 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 // Set up pacakge manager for the other user.
478 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
481
482 dpm.setActiveAdmin(admin1, /* replace =*/ false);
483
484 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
485 dpm.setActiveAdmin(admin2, /* replace =*/ false);
486
487
488 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
489 assertTrue(dpm.isAdminActive(admin1));
490 assertFalse(dpm.isAdminActive(admin2));
491
492 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
493 assertFalse(dpm.isAdminActive(admin1));
494 assertTrue(dpm.isAdminActive(admin2));
495 }
496
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 /**
498 * Test for:
499 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800500 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700501 */
502 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
503 // 1. Make sure the caller has proper permissions.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506 dpm.setActiveAdmin(admin1, /* replace =*/ false);
507 assertTrue(dpm.isAdminActive(admin1));
508
509 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
511 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700512 }
513
514 /**
515 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800516 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
517 * BIND_DEVICE_ADMIN.
518 */
519 public void testSetActiveAdmin_permissionCheck() throws Exception {
520 // 1. Make sure the caller has proper permissions.
521 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
522
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(IllegalArgumentException.class,
524 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
525 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800526 assertFalse(dpm.isAdminActive(adminNoPerm));
527
528 // Change the target API level to MNC. Now it can be set as DA.
529 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
530 VERSION_CODES.M);
531 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
532 assertTrue(dpm.isAdminActive(adminNoPerm));
533
534 // TODO Test the "load from the file" case where DA will still be loaded even without
535 // BIND_DEVICE_ADMIN and target API is N.
536 }
537
538 /**
539 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700540 * {@link DevicePolicyManager#removeActiveAdmin}
541 */
542 public void testRemoveActiveAdmin_SecurityException() {
543 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
544
545 // Add admin.
546
547 dpm.setActiveAdmin(admin1, /* replace =*/ false);
548
549 assertTrue(dpm.isAdminActive(admin1));
550
551 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
552
553 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100554 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
555 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700556
557 // Try to remove active admin with a different caller userid should fail too, without
558 // having MANAGE_DEVICE_ADMINS.
559 mContext.callerPermissions.clear();
560
Makoto Onukid932f762015-09-29 16:53:38 -0700561 // Change the caller, and call into DPMS directly with a different user-id.
562
Makoto Onukif76b06a2015-09-22 15:03:44 -0700563 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100564 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
565 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 }
567
568 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800569 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
570 * (because we can't send the remove broadcast).
571 */
572 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
573 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
574
575 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
576
577 // Add admin.
578
579 dpm.setActiveAdmin(admin1, /* replace =*/ false);
580
581 assertTrue(dpm.isAdminActive(admin1));
582
583 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
584
585 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100586 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100588 assertExpectException(IllegalStateException.class,
589 /* messageRegex= */ "User must be running and unlocked",
590 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800593 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
594 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800595
596 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100597 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598 .thenReturn(true);
599
600 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700601 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800602 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
603 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800604 }
605
606 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 * Test for:
608 * {@link DevicePolicyManager#removeActiveAdmin}
609 */
Makoto Onukid932f762015-09-29 16:53:38 -0700610 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700611 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
612
613 // Add admin1.
614
615 dpm.setActiveAdmin(admin1, /* replace =*/ false);
616
617 assertTrue(dpm.isAdminActive(admin1));
618 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
619
620 // Different user, but should work, because caller has proper permissions.
621 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700622
623 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700624 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700627 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800628 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
629 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700630
631 // TODO DO Still can't be removed in this case.
632 }
633
634 /**
635 * Test for:
636 * {@link DevicePolicyManager#removeActiveAdmin}
637 */
638 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
639 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
640 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
641
642 // Add admin1.
643
644 dpm.setActiveAdmin(admin1, /* replace =*/ false);
645
646 assertTrue(dpm.isAdminActive(admin1));
647 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
648
649 // Broadcast from saveSettingsLocked().
650 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
651 MockUtils.checkIntentAction(
652 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
653 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
654
655 // Remove. No permissions, but same user, so it'll work.
656 mContext.callerPermissions.clear();
657 dpm.removeActiveAdmin(admin1);
658
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
660 MockUtils.checkIntentAction(
661 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
662 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
663 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100664 eq(AppOpsManager.OP_NONE),
665 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700667 eq(dpms.mHandler),
668 eq(Activity.RESULT_OK),
669 isNull(String.class),
670 isNull(Bundle.class));
671
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700672 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800673 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
674 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700675
676 // Again broadcast from saveSettingsLocked().
677 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
678 MockUtils.checkIntentAction(
679 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
680 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
681
682 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700683 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700684
Sudheer Shanka101c3532018-01-08 16:28:42 -0800685 public void testRemoveActiveAdmin_multipleAdminsInUser() {
686 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
687 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
688
689 // Add admin1.
690 dpm.setActiveAdmin(admin1, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin1));
693 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Add admin2.
696 dpm.setActiveAdmin(admin2, /* replace =*/ false);
697
698 assertTrue(dpm.isAdminActive(admin2));
699 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
700
701 // Broadcast from saveSettingsLocked().
702 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
703 MockUtils.checkIntentAction(
704 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
705 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
706
707 // Remove. No permissions, but same user, so it'll work.
708 mContext.callerPermissions.clear();
709 dpm.removeActiveAdmin(admin1);
710
711 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
712 MockUtils.checkIntentAction(
713 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
714 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
715 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100716 eq(AppOpsManager.OP_NONE),
717 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800718 any(BroadcastReceiver.class),
719 eq(dpms.mHandler),
720 eq(Activity.RESULT_OK),
721 isNull(String.class),
722 isNull(Bundle.class));
723
724 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
725 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800726 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800727 eq(DpmMockContext.CALLER_USER_HANDLE));
728
729 // Again broadcast from saveSettingsLocked().
730 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
731 MockUtils.checkIntentAction(
732 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
733 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
734 }
735
736 /**
737 * Test for:
738 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
739 */
740 public void testForceRemoveActiveAdmin() throws Exception {
741 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
742
743 // Add admin.
744 setupPackageInPackageManager(admin1.getPackageName(),
745 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
746 /* appId= */ 10138,
747 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
748 dpm.setActiveAdmin(admin1, /* replace =*/ false);
749 assertTrue(dpm.isAdminActive(admin1));
750
751 // Calling from a non-shell uid should fail with a SecurityException
752 mContext.binder.callingUid = 123456;
753 assertExpectException(SecurityException.class,
754 /* messageRegex =*/ "Non-shell user attempted to call",
755 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
756
757 mContext.binder.callingUid = Process.SHELL_UID;
758 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
759
760 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
761 // Verify
762 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
763 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
764 null, DpmMockContext.CALLER_USER_HANDLE);
765 }
766
Makoto Onukib643fb02015-09-22 15:03:44 -0700767 /**
Rubin Xu19854862019-08-15 16:37:23 +0100768 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000769 *
770 * Validates that when the password for a user changes, the notification broadcast intent
771 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
772 * addition to ones in the original user.
773 */
774 public void testSetActivePasswordState_sendToProfiles() throws Exception {
775 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
776
777 final int MANAGED_PROFILE_USER_ID = 78;
778 final int MANAGED_PROFILE_ADMIN_UID =
779 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
780
781 // Setup device owner.
782 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
783 mContext.packageName = admin1.getPackageName();
784 setupDeviceOwner();
785
786 // Add a managed profile belonging to the system user.
787 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
788
789 // Change the parent user's password.
790 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
791
792 // Both the device owner and the managed profile owner should receive this broadcast.
793 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
794 intent.setComponent(admin1);
795 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
796
797 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
798 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100799 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
800 eq(null),
801 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000802 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
803 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100804 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
805 eq(null),
806 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000807 }
808
809 /**
Rubin Xu19854862019-08-15 16:37:23 +0100810 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000811 *
812 * Validates that when the password for a managed profile changes, the notification broadcast
813 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
814 * its parent.
815 */
816 public void testSetActivePasswordState_notSentToParent() throws Exception {
817 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
818
819 final int MANAGED_PROFILE_USER_ID = 78;
820 final int MANAGED_PROFILE_ADMIN_UID =
821 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
822
823 // Setup device owner.
824 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
825 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100826 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000827 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
828 setupDeviceOwner();
829
830 // Add a managed profile belonging to the system user.
831 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
832
833 // Change the profile's password.
834 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
835
836 // Both the device owner and the managed profile owner should receive this broadcast.
837 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
838 intent.setComponent(admin1);
839 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
840
841 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
842 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100843 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
844 eq(null),
845 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000846 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
847 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100848 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
849 eq(null),
850 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000851 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100852
Robin Leed2a73ed2016-12-19 09:07:16 +0000853 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000854 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700855 */
856 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000857 setDeviceOwner();
858
859 // Try to set a profile owner on the same user, which should fail.
860 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
861 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100862 assertExpectException(IllegalStateException.class,
863 /* messageRegex= */ "already has a device owner",
864 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000865
866 // DO admin can't be deactivated.
867 dpm.removeActiveAdmin(admin1);
868 assertTrue(dpm.isAdminActive(admin1));
869
870 // TODO Test getDeviceOwnerName() too. To do so, we need to change
871 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
872 }
873
874 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700875 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800876 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700877 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
878 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
879
Makoto Onukid932f762015-09-29 16:53:38 -0700880 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
882
Makoto Onukid932f762015-09-29 16:53:38 -0700883 // Make sure admin1 is installed on system user.
884 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700885
Makoto Onukic8a5a552015-11-19 14:29:12 -0800886 // Check various get APIs.
887 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
888
Makoto Onukib643fb02015-09-22 15:03:44 -0700889 // DO needs to be an DA.
890 dpm.setActiveAdmin(admin1, /* replace =*/ false);
891
892 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700893 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700894
Makoto Onukic8a5a552015-11-19 14:29:12 -0800895 // getDeviceOwnerComponent should return the admin1 component.
896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
897 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
898
899 // Check various get APIs.
900 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
901
902 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
903 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
904 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
905 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
906
907 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
908
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000909 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100910 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000911 eq(admin1.getPackageName()));
912
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100914 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700915 eq(UserHandle.USER_SYSTEM), eq(false));
916
917 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
918 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
919 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
920
Makoto Onukic8a5a552015-11-19 14:29:12 -0800921 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700922 }
923
Makoto Onukic8a5a552015-11-19 14:29:12 -0800924 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
925 final int origCallingUser = mContext.binder.callingUid;
926 final List origPermissions = new ArrayList(mContext.callerPermissions);
927 mContext.callerPermissions.clear();
928
929 mContext.callerPermissions.add(permission.MANAGE_USERS);
930
931 mContext.binder.callingUid = Process.SYSTEM_UID;
932
933 // TODO Test getDeviceOwnerName() too. To do so, we need to change
934 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
935 if (hasDeviceOwner) {
936 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
937 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
938 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
939
940 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
941 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
942 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
943 } else {
944 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
945 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
946 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
947
948 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
949 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
950 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
951 }
952
953 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
954 if (hasDeviceOwner) {
955 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
956 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
957 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
958
959 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
960 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
961 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
962 } else {
963 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
964 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
965 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
966
967 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
968 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
969 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
970 }
971
972 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
973 // Still with MANAGE_USERS.
974 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
975 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
976 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
977
978 if (hasDeviceOwner) {
979 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
982 } else {
983 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
984 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
985 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
986 }
987
988 mContext.binder.callingUid = Process.SYSTEM_UID;
989 mContext.callerPermissions.remove(permission.MANAGE_USERS);
990 // System can still call "OnAnyUser" without MANAGE_USERS.
991 if (hasDeviceOwner) {
992 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
993 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
994 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
995
996 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
997 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
998 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
999 } else {
1000 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1001 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1002 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1003
1004 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1005 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1006 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1007 }
1008
1009 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1010 // Still no MANAGE_USERS.
1011 if (hasDeviceOwner) {
1012 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1013 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1014 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1015 } else {
1016 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1017 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1018 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1019 }
1020
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001021 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1022 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1023 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1024 dpm::getDeviceOwnerComponentOnAnyUser);
1025 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1026 dpm::getDeviceOwnerUserId);
1027 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1028 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001029
1030 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1031 // Still no MANAGE_USERS.
1032 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1033 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1034 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1035
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001036 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1037 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1038 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1039 dpm::getDeviceOwnerComponentOnAnyUser);
1040 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1041 dpm::getDeviceOwnerUserId);
1042 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1043 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001044
1045 // Restore.
1046 mContext.binder.callingUid = origCallingUser;
1047 mContext.callerPermissions.addAll(origPermissions);
1048 }
1049
1050
Makoto Onukib643fb02015-09-22 15:03:44 -07001051 /**
1052 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1053 */
1054 public void testSetDeviceOwner_noSuchPackage() {
1055 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001056 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001057 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1058 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1059
1060 // Call from a process on the system user.
1061 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1062
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001063 assertExpectException(IllegalArgumentException.class,
1064 /* messageRegex= */ "Invalid component",
1065 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001066 }
1067
1068 public void testSetDeviceOwner_failures() throws Exception {
1069 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1070 }
1071
Makoto Onukia52562c2015-10-01 16:12:31 -07001072 public void testClearDeviceOwner() throws Exception {
1073 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001074 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001075 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1076 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1077
1078 // Set admin1 as a DA to the secondary user.
1079 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1080
1081 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1082
1083 // Set admin 1 as the DO to the system user.
1084
1085 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1086 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1087 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1088 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1089
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001090 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001091 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001092 eq(admin1.getPackageName()));
1093
Makoto Onukic8a5a552015-11-19 14:29:12 -08001094 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001095
Makoto Onuki90b89652016-01-28 14:44:18 -08001096 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001097 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001098 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001099
1100 assertTrue(dpm.isAdminActive(admin1));
1101 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1102
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001104 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001105
1106 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001107 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1108 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001109
1110 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001111 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001112 assertExpectException(IllegalStateException.class,
1113 /* messageRegex= */ "User must be running and unlocked",
1114 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001115
Pavel Grafov75c0a892017-05-18 17:28:27 +01001116 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1117 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001118 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1119
1120 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001121 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001122
Pavel Grafov75c0a892017-05-18 17:28:27 +01001123 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001124 eq(false),
1125 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1126
Pavel Grafov75c0a892017-05-18 17:28:27 +01001127 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001128 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001129 eq(null),
1130 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001131
Sudheer Shanka101c3532018-01-08 16:28:42 -08001132 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1133 null, UserHandle.USER_SYSTEM);
1134
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001135 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001136
1137 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1138 // and once for clearing it.
1139 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1140 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1141 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001142 // TODO Check other calls.
1143 }
1144
1145 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1146 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001147 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001148 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1149 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1150
1151 // Set admin1 as a DA to the secondary user.
1152 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1153
1154 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1155
1156 // Set admin 1 as the DO to the system user.
1157
1158 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1159 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1160 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1161 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1162
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001163 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001164 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001165 eq(admin1.getPackageName()));
1166
Makoto Onukic8a5a552015-11-19 14:29:12 -08001167 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001168
1169 // Now call clear from the secondary user, which should throw.
1170 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1171
1172 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001173 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001174 eq(admin1.getPackageName()),
1175 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001176 assertExpectException(SecurityException.class,
1177 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1178 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001179
Makoto Onukic8a5a552015-11-19 14:29:12 -08001180 // DO shouldn't be removed.
1181 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001182 }
1183
Makoto Onukib643fb02015-09-22 15:03:44 -07001184 public void testSetProfileOwner() throws Exception {
1185 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001186
Makoto Onuki90b89652016-01-28 14:44:18 -08001187 // PO admin can't be deactivated.
1188 dpm.removeActiveAdmin(admin1);
1189 assertTrue(dpm.isAdminActive(admin1));
1190
Makoto Onuki803d6752015-10-30 12:58:39 -07001191 // Try setting DO on the same user, which should fail.
1192 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001193 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1194 runAsCaller(mServiceContext, dpms, dpm -> {
1195 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001196 assertExpectException(IllegalStateException.class,
1197 /* messageRegex= */ "already has a profile owner",
1198 () -> dpm.setDeviceOwner(admin2, "owner-name",
1199 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001200 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001201 }
1202
Makoto Onuki90b89652016-01-28 14:44:18 -08001203 public void testClearProfileOwner() throws Exception {
1204 setAsProfileOwner(admin1);
1205
1206 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1207
1208 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1209 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1210
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001211 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001212 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001213 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001214 assertExpectException(IllegalStateException.class,
1215 /* messageRegex= */ "User must be running and unlocked",
1216 () -> dpm.clearProfileOwner(admin1));
1217
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001218 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001219 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001220 dpm.clearProfileOwner(admin1);
1221
1222 // Check
1223 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001224 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001225 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1226 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001227 }
1228
Makoto Onukib643fb02015-09-22 15:03:44 -07001229 public void testSetProfileOwner_failures() throws Exception {
1230 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1231 }
1232
Makoto Onukia52562c2015-10-01 16:12:31 -07001233 public void testGetDeviceOwnerAdminLocked() throws Exception {
1234 checkDeviceOwnerWithMultipleDeviceAdmins();
1235 }
1236
1237 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1238 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1239 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1240 // make sure it gets the right component from the right user.
1241
1242 final int ANOTHER_USER_ID = 100;
1243 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1244
Pavel Grafov75c0a892017-05-18 17:28:27 +01001245 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001246
1247 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001248 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1250 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1251
1252 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1253
Pavel Grafov75c0a892017-05-18 17:28:27 +01001254 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001255
Makoto Onukia52562c2015-10-01 16:12:31 -07001256 // Make sure the admin packge is installed to each user.
1257 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1258 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1259
1260 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1261 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1262
1263 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1264
1265
1266 // Set active admins to the users.
1267 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1268 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1269
1270 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1271 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1272
1273 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1274
1275 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001276 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001277 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1278
Makoto Onukic8a5a552015-11-19 14:29:12 -08001279 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001280
1281 // Then check getDeviceOwnerAdminLocked().
1282 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1283 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1284 }
1285
1286 /**
1287 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001288 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1289 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001290 *
1291 * We didn't use to persist the DO component class name, but now we do, and the above method
1292 * finds the right component from a package name upon migration.
1293 */
1294 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001295 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001296 checkDeviceOwnerWithMultipleDeviceAdmins();
1297
1298 // Overwrite the device owner setting and clears the clas name.
1299 dpms.mOwners.setDeviceOwner(
1300 new ComponentName(admin2.getPackageName(), ""),
1301 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1302 dpms.mOwners.writeDeviceOwner();
1303
1304 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001305 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001306
1307 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001308 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001309 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001310 initializeDpms();
1311
1312 // Now the DO component name is a full name.
1313 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1314 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001315 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001316 }
1317
Makoto Onukib643fb02015-09-22 15:03:44 -07001318 public void testSetGetApplicationRestriction() {
1319 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001320 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001321
1322 {
1323 Bundle rest = new Bundle();
1324 rest.putString("KEY_STRING", "Foo1");
1325 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1326 }
1327
1328 {
1329 Bundle rest = new Bundle();
1330 rest.putString("KEY_STRING", "Foo2");
1331 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1332 }
1333
1334 {
1335 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1336 assertNotNull(returned);
1337 assertEquals(returned.size(), 1);
1338 assertEquals(returned.get("KEY_STRING"), "Foo1");
1339 }
1340
1341 {
1342 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1343 assertNotNull(returned);
1344 assertEquals(returned.size(), 1);
1345 assertEquals(returned.get("KEY_STRING"), "Foo2");
1346 }
1347
1348 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1349 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1350 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001351
Edman Anjosf9946772016-11-28 16:35:15 +01001352 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001353 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1354 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001355 *
1356 * @param packageName the name of the package to be setup
1357 * @param appId the application ID to be given to the package
1358 * @return the UID of the package as known by the mock package manager
1359 */
1360 private int setupPackageInPackageManager(final String packageName, final int appId)
1361 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001362 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001363 ApplicationInfo.FLAG_HAS_CODE);
1364 }
1365
1366 /**
1367 * Setup a package in the package manager mock. Useful for faking installed applications.
1368 *
1369 * @param packageName the name of the package to be setup
1370 * @param userId the user id where the package will be "installed"
1371 * @param appId the application ID to be given to the package
1372 * @param flags flags to set in the ApplicationInfo for this package
1373 * @return the UID of the package as known by the mock package manager
1374 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001375 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1376 int flags) throws Exception {
1377 final int uid = UserHandle.getUid(userId, appId);
1378 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001379 final PackageInfo pi = new PackageInfo();
1380 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001381 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001383 eq(packageName),
1384 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001385 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001386 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001387 eq(packageName),
1388 anyInt(),
1389 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001390 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001391 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001392 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001393 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001394 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001395 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001396 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001397 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001398 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001399 return uid;
1400 }
1401
Robin Lee7f5c91c2017-02-08 21:27:02 +00001402 public void testCertificateDisclosure() throws Exception {
1403 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1404 final UserHandle user = UserHandle.of(userId);
1405
1406 mContext.applicationInfo = new ApplicationInfo();
1407 mContext.callerPermissions.add(permission.MANAGE_USERS);
1408 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001409 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001410 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1411
Robin Leeabaa0692017-02-20 20:54:22 +00001412 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1413 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001414
1415 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1416 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1417
1418 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001419 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001420 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001421 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001422 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001423 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001424 .cancelAsUser(anyString(), anyInt(), eq(user));
1425
1426 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001427 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001428 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001429 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1430 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001431 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001432 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001433 .notifyAsUser(anyString(), anyInt(), argThat(
1434 new BaseMatcher<Notification>() {
1435 @Override
1436 public boolean matches(Object item) {
1437 final Notification noti = (Notification) item;
1438 return TEST_STRING.equals(
1439 noti.extras.getString(Notification.EXTRA_TITLE));
1440 }
1441 @Override
1442 public void describeTo(Description description) {
1443 description.appendText(
1444 "Notification{title=\"" + TEST_STRING + "\"}");
1445 }
1446 }), eq(user));
1447 }
1448
Edman Anjosf9946772016-11-28 16:35:15 +01001449 /**
1450 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1451 * privileges can acually be exercised by a delegate are not covered here.
1452 */
1453 public void testDelegation() throws Exception {
1454 setAsProfileOwner(admin1);
1455
1456 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1457
1458 // Given two packages
1459 final String CERT_DELEGATE = "com.delegate.certs";
1460 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1461 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1462 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1463 20989);
1464
1465 // On delegation
1466 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1467 mContext.packageName = admin1.getPackageName();
1468 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1469 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1470
1471 // DPMS correctly stores and retrieves the delegates
1472 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1473 assertEquals(2, policy.mDelegationMap.size());
1474 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1475 DELEGATION_CERT_INSTALL);
1476 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1477 DELEGATION_CERT_INSTALL);
1478 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1479 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1480 DELEGATION_APP_RESTRICTIONS);
1481 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1482 DELEGATION_APP_RESTRICTIONS);
1483 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1484
1485 // On calling install certificate APIs from an unauthorized process
1486 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1487 mContext.packageName = RESTRICTIONS_DELEGATE;
1488
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001489 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1490 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001491
1492 // On calling install certificate APIs from an authorized process
1493 mContext.binder.callingUid = CERT_DELEGATE_UID;
1494 mContext.packageName = CERT_DELEGATE;
1495
1496 // DPMS executes without a SecurityException
1497 try {
1498 dpm.installCaCert(null, null);
1499 } catch (SecurityException unexpected) {
1500 fail("Threw SecurityException on authorized access");
1501 } catch (NullPointerException expected) {
1502 }
1503
1504 // On removing a delegate
1505 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1506 mContext.packageName = admin1.getPackageName();
1507 dpm.setCertInstallerPackage(admin1, null);
1508
1509 // DPMS does not allow access to ex-delegate
1510 mContext.binder.callingUid = CERT_DELEGATE_UID;
1511 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001512 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1513 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001514
1515 // But still allows access to other existing delegates
1516 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1517 mContext.packageName = RESTRICTIONS_DELEGATE;
1518 try {
1519 dpm.getApplicationRestrictions(null, "pkg");
1520 } catch (SecurityException expected) {
1521 fail("Threw SecurityException on authorized access");
1522 }
1523 }
1524
Esteban Talaverabf60f722015-12-10 16:26:44 +00001525 public void testApplicationRestrictionsManagingApp() throws Exception {
1526 setAsProfileOwner(admin1);
1527
Rubin Xued1928a2016-02-11 17:23:06 +00001528 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001529 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001530 final String nonDelegateExceptionMessageRegex =
1531 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001532 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001533 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1534 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001535
Esteban Talaverabf60f722015-12-10 16:26:44 +00001536 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1537 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001538 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1539 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001540 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001541 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001542 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001543 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1544 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001545
1546 // Check via the profile owner that no restrictions were set.
1547 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001548 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001549 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1550
Rubin Xued1928a2016-02-11 17:23:06 +00001551 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001552 assertExpectException(PackageManager.NameNotFoundException.class,
1553 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1554 () -> dpm.setApplicationRestrictionsManagingPackage(
1555 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001556
Esteban Talaverabf60f722015-12-10 16:26:44 +00001557 // Let appRestrictionsManagerPackage manage app restrictions
1558 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1559 assertEquals(appRestrictionsManagerPackage,
1560 dpm.getApplicationRestrictionsManagingPackage(admin1));
1561
1562 // Now that package should be able to set and retrieve app restrictions.
1563 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001564 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001565 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1566 dpm.setApplicationRestrictions(null, "pkg1", rest);
1567 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1568 assertEquals(1, returned.size(), 1);
1569 assertEquals("Foo1", returned.get("KEY_STRING"));
1570
1571 // The same app running on a separate user shouldn't be able to manage app restrictions.
1572 mContext.binder.callingUid = UserHandle.getUid(
1573 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1574 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001575 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1576 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001577
1578 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1579 // too.
1580 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001581 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001582 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1583 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1584 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1585
1586 // Removing the ability for the package to manage app restrictions.
1587 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1588 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1589 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001590 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001591 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001592 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1593 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001594 }
1595
Makoto Onukia4f11972015-10-01 13:19:58 -07001596 public void testSetUserRestriction_asDo() throws Exception {
1597 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001598 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001599 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1600 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1601
1602 // First, set DO.
1603
1604 // Call from a process on the system user.
1605 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1606
1607 // Make sure admin1 is installed on system user.
1608 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001609
1610 // Call.
1611 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001612 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001613 UserHandle.USER_SYSTEM));
1614
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001615 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001616 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001617 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001618 DpmTestUtils.assertRestrictions(
1619 DpmTestUtils.newRestrictions(defaultRestrictions),
1620 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1621 );
1622 DpmTestUtils.assertRestrictions(
1623 DpmTestUtils.newRestrictions(defaultRestrictions),
1624 dpm.getUserRestrictions(admin1)
1625 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001626 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001627 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001628 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001629 eq(true) /* isDeviceOwner */,
1630 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001631 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001632 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001633
1634 for (String restriction : defaultRestrictions) {
1635 dpm.clearUserRestriction(admin1, restriction);
1636 }
1637
Esteban Talavera548a04b2016-12-20 15:22:30 +00001638 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001639 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001640
1641 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001642 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001644 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1645 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001646 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647
Makoto Onukia4f11972015-10-01 13:19:58 -07001648 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001649 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1652 UserManager.DISALLOW_ADD_USER),
1653 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001654 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001655
Makoto Onuki068c54a2015-10-13 14:34:03 -07001656 DpmTestUtils.assertRestrictions(
1657 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001658 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001659 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1660 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001661 DpmTestUtils.assertRestrictions(
1662 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001663 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001664 dpm.getUserRestrictions(admin1)
1665 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001666
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001668 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001669 eq(UserHandle.USER_SYSTEM),
1670 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001671 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001672 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001673
Makoto Onuki068c54a2015-10-13 14:34:03 -07001674 DpmTestUtils.assertRestrictions(
1675 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1676 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1677 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001678 DpmTestUtils.assertRestrictions(
1679 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1680 dpm.getUserRestrictions(admin1)
1681 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001682
1683 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001684 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001685 eq(UserHandle.USER_SYSTEM),
1686 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001687 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001688 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001689
Esteban Talavera548a04b2016-12-20 15:22:30 +00001690 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001691
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001692 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1693 // DO sets them, the scope is global.
1694 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001695 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001696 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001697 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001700 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1701 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001702 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001703
1704 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1705 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001706 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001707
1708 // More tests.
1709 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001710 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001712 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1713 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001714 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001715
1716 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001717 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 UserManager.DISALLOW_ADD_USER),
1721 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001722 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723
1724 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001725 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001726 eq(UserHandle.USER_SYSTEM),
1727 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001728 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001729 UserManager.DISALLOW_ADD_USER),
1730 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001731 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001732 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001733
Eric Sandnessca5969d2018-08-10 13:28:46 +01001734 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1735 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1736 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001737
Eric Sandnessca5969d2018-08-10 13:28:46 +01001738 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1739 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740
Eric Sandnessca5969d2018-08-10 13:28:46 +01001741 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1742 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1743 () -> dpm.setCameraDisabled(admin1, true));
1744 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1745
1746 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1747 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1748 () -> dpm.setKeyguardDisabledFeatures(admin1,
1749 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1750 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1751
1752 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1753 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1754 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1755 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1756
1757 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1758 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1759 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1760 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001761 }
1762
1763 public void testSetUserRestriction_asPo() {
1764 setAsProfileOwner(admin1);
1765
Makoto Onuki068c54a2015-10-13 14:34:03 -07001766 DpmTestUtils.assertRestrictions(
1767 DpmTestUtils.newRestrictions(),
1768 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1769 .ensureUserRestrictions()
1770 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001771
1772 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001773 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001774 eq(DpmMockContext.CALLER_USER_HANDLE),
1775 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001776 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001777 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001778
Makoto Onukia4f11972015-10-01 13:19:58 -07001779 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001780 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001781 eq(DpmMockContext.CALLER_USER_HANDLE),
1782 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1783 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001784 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001785 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001786
Makoto Onuki068c54a2015-10-13 14:34:03 -07001787 DpmTestUtils.assertRestrictions(
1788 DpmTestUtils.newRestrictions(
1789 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1790 UserManager.DISALLOW_OUTGOING_CALLS
1791 ),
1792 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1793 .ensureUserRestrictions()
1794 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001795 DpmTestUtils.assertRestrictions(
1796 DpmTestUtils.newRestrictions(
1797 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1798 UserManager.DISALLOW_OUTGOING_CALLS
1799 ),
1800 dpm.getUserRestrictions(admin1)
1801 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001802
1803 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001804 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 eq(DpmMockContext.CALLER_USER_HANDLE),
1806 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001807 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001808 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001809
1810 DpmTestUtils.assertRestrictions(
1811 DpmTestUtils.newRestrictions(
1812 UserManager.DISALLOW_OUTGOING_CALLS
1813 ),
1814 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1815 .ensureUserRestrictions()
1816 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001817 DpmTestUtils.assertRestrictions(
1818 DpmTestUtils.newRestrictions(
1819 UserManager.DISALLOW_OUTGOING_CALLS
1820 ),
1821 dpm.getUserRestrictions(admin1)
1822 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001823
1824 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001825 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001826 eq(DpmMockContext.CALLER_USER_HANDLE),
1827 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001828 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001829 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001830
Makoto Onuki068c54a2015-10-13 14:34:03 -07001831 DpmTestUtils.assertRestrictions(
1832 DpmTestUtils.newRestrictions(),
1833 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1834 .ensureUserRestrictions()
1835 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001836 DpmTestUtils.assertRestrictions(
1837 DpmTestUtils.newRestrictions(),
1838 dpm.getUserRestrictions(admin1)
1839 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001840
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001841 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1842 // though when DO sets them they'll be applied globally.
1843 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001844 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001846 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001847 eq(DpmMockContext.CALLER_USER_HANDLE),
1848 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1849 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001850 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001851 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001852
1853 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001854 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001855 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001856 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001857 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001858 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001859 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001860
Makoto Onukia4f11972015-10-01 13:19:58 -07001861 // TODO Make sure restrictions are written to the file.
1862 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001863
Esteban Talavera548a04b2016-12-20 15:22:30 +00001864
1865 public void testDefaultEnabledUserRestrictions() throws Exception {
1866 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1867 mContext.callerPermissions.add(permission.MANAGE_USERS);
1868 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1869 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1870
1871 // First, set DO.
1872
1873 // Call from a process on the system user.
1874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1875
1876 // Make sure admin1 is installed on system user.
1877 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1878
1879 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1880 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1881 UserHandle.USER_SYSTEM));
1882
1883 // Check that the user restrictions that are enabled by default are set. Then unset them.
1884 String[] defaultRestrictions = UserRestrictionsUtils
1885 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1886 assertTrue(defaultRestrictions.length > 0);
1887 DpmTestUtils.assertRestrictions(
1888 DpmTestUtils.newRestrictions(defaultRestrictions),
1889 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1890 );
1891 DpmTestUtils.assertRestrictions(
1892 DpmTestUtils.newRestrictions(defaultRestrictions),
1893 dpm.getUserRestrictions(admin1)
1894 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001895 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001896 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001897 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001898 eq(true) /* isDeviceOwner */,
1899 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001900 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001901 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001902
1903 for (String restriction : defaultRestrictions) {
1904 dpm.clearUserRestriction(admin1, restriction);
1905 }
1906
1907 assertNoDeviceOwnerRestrictions();
1908
1909 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001910 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001911 initializeDpms();
1912 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1913 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1914
1915 assertNoDeviceOwnerRestrictions();
1916
1917 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1918 // is set as it wasn't enabled during setDeviceOwner.
1919 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1920 assertFalse(UserRestrictionsUtils
1921 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1922 UserRestrictionsUtils
1923 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1924 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001925 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001926 initializeDpms();
1927 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1928 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1929
1930 DpmTestUtils.assertRestrictions(
1931 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1932 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1933 );
1934 DpmTestUtils.assertRestrictions(
1935 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1936 dpm.getUserRestrictions(admin1)
1937 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001938 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001939 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001940 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001941 eq(true) /* isDeviceOwner */,
1942 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001943 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001944 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001945
1946 // Remove the restriction.
1947 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1948
1949 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1950 initializeDpms();
1951 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1952 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1953 assertNoDeviceOwnerRestrictions();
1954 } finally {
1955 UserRestrictionsUtils
1956 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1957 }
1958 }
1959
1960 private void assertNoDeviceOwnerRestrictions() {
1961 DpmTestUtils.assertRestrictions(
1962 DpmTestUtils.newRestrictions(),
1963 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1964 );
1965 DpmTestUtils.assertRestrictions(
1966 DpmTestUtils.newRestrictions(),
1967 dpm.getUserRestrictions(admin1)
1968 );
1969 }
1970
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001971 public void testGetMacAddress() throws Exception {
1972 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1973 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1974 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1975
1976 // In this test, change the caller user to "system".
1977 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1978
1979 // Make sure admin1 is installed on system user.
1980 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1981
1982 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001983 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1984 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001985
1986 // DO needs to be an DA.
1987 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1988 assertTrue(dpm.isAdminActive(admin1));
1989
1990 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001991 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1992 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001993
1994 // Test 3. Caller has PO, but not DO.
1995 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001996 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1997 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001998
1999 // Remove PO.
2000 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002001 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002002 // Test 4, Caller is DO now.
2003 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2004
xshu425b9a62018-12-13 14:18:18 -08002005 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002006 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002007
xshu425b9a62018-12-13 14:18:18 -08002008 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2009 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002010 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002011
2012 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002013 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2014 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002015 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002016 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002017
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002018 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002019 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2020 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2021
2022 // In this test, change the caller user to "system".
2023 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2024
2025 // Make sure admin1 is installed on system user.
2026 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2027
2028 // Set admin1 as DA.
2029 dpm.setActiveAdmin(admin1, false);
2030 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002031 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2032 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002033
2034 // Set admin1 as PO.
2035 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002036 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2037 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002038
2039 // Remove PO and add DO.
2040 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002041 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002042 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2043
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002044 // admin1 is DO.
2045 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002046 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002047 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002048 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2049 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002050
2051 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002052 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002053 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002054 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2055 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002056
2057 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002058 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002059 dpm.reboot(admin1);
2060 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002061
2062 public void testSetGetSupportText() {
2063 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2064 dpm.setActiveAdmin(admin1, true);
2065 dpm.setActiveAdmin(admin2, true);
2066 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2067
2068 // Null default support messages.
2069 {
2070 assertNull(dpm.getLongSupportMessage(admin1));
2071 assertNull(dpm.getShortSupportMessage(admin1));
2072 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2073 assertNull(dpm.getShortSupportMessageForUser(admin1,
2074 DpmMockContext.CALLER_USER_HANDLE));
2075 assertNull(dpm.getLongSupportMessageForUser(admin1,
2076 DpmMockContext.CALLER_USER_HANDLE));
2077 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2078 }
2079
2080 // Only system can call the per user versions.
2081 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002082 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2083 () -> dpm.getShortSupportMessageForUser(admin1,
2084 DpmMockContext.CALLER_USER_HANDLE));
2085 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2086 () -> dpm.getLongSupportMessageForUser(admin1,
2087 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002088 }
2089
2090 // Can't set message for admin in another uid.
2091 {
2092 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002093 assertExpectException(SecurityException.class,
2094 /* messageRegex= */ "is not owned by uid",
2095 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002096 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2097 }
2098
2099 // Set/Get short returns what it sets and other admins text isn't changed.
2100 {
2101 final String supportText = "Some text to test with.";
2102 dpm.setShortSupportMessage(admin1, supportText);
2103 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2104 assertNull(dpm.getLongSupportMessage(admin1));
2105 assertNull(dpm.getShortSupportMessage(admin2));
2106
2107 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2108 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2109 DpmMockContext.CALLER_USER_HANDLE));
2110 assertNull(dpm.getShortSupportMessageForUser(admin2,
2111 DpmMockContext.CALLER_USER_HANDLE));
2112 assertNull(dpm.getLongSupportMessageForUser(admin1,
2113 DpmMockContext.CALLER_USER_HANDLE));
2114 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2115
2116 dpm.setShortSupportMessage(admin1, null);
2117 assertNull(dpm.getShortSupportMessage(admin1));
2118 }
2119
2120 // Set/Get long returns what it sets and other admins text isn't changed.
2121 {
2122 final String supportText = "Some text to test with.\nWith more text.";
2123 dpm.setLongSupportMessage(admin1, supportText);
2124 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2125 assertNull(dpm.getShortSupportMessage(admin1));
2126 assertNull(dpm.getLongSupportMessage(admin2));
2127
2128 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2129 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2130 DpmMockContext.CALLER_USER_HANDLE));
2131 assertNull(dpm.getLongSupportMessageForUser(admin2,
2132 DpmMockContext.CALLER_USER_HANDLE));
2133 assertNull(dpm.getShortSupportMessageForUser(admin1,
2134 DpmMockContext.CALLER_USER_HANDLE));
2135 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2136
2137 dpm.setLongSupportMessage(admin1, null);
2138 assertNull(dpm.getLongSupportMessage(admin1));
2139 }
2140 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002141
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002142 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002143 setAsProfileOwner(admin1);
2144
2145 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002146 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002147
2148 // Setup
2149 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2150 final String package1 = "com.example.one";
2151 final String package2 = "com.example.two";
2152 pkgsToRestrict.add(package1);
2153 pkgsToRestrict.add(package2);
2154 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2155 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002156 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002157
2158 // Verify
2159 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002160 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002161 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2162 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2163 eq(DpmMockContext.CALLER_USER_HANDLE));
2164
2165 // Setup
2166 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002167 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002168
2169 // Verify
2170 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002171 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002172 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2173 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2174 eq(DpmMockContext.CALLER_USER_HANDLE));
2175 }
2176
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002177 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002178 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2179 dpm.setActiveAdmin(admin1, true);
2180 assertTrue(dpm.isAdminActive(admin1));
2181 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2182
2183 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002184 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002185 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002186 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002187 }
2188
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002189 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002190 setAsProfileOwner(admin1);
2191
2192 // Setup
2193 final ArrayList<String> emptyList = new ArrayList<>();
2194 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2195 final String package1 = "com.example.one";
2196 final String package2 = "com.example.two";
2197 final String package3 = "com.example.three";
2198 pkgsToRestrict.add(package1);
2199 pkgsToRestrict.add(package2);
2200 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2201 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002203
2204 // Verify
2205 assertEquals(emptyList, excludedPkgs);
2206 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2207 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002208 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002209 DpmMockContext.CALLER_USER_HANDLE));
2210 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002211 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002212 DpmMockContext.CALLER_USER_HANDLE));
2213 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002214 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002215 DpmMockContext.CALLER_USER_HANDLE));
2216 }
2217
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002218 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002219 setAsProfileOwner(admin1);
2220 assertExpectException(SecurityException.class,
2221 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002222 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002223 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2224 dpm.clearProfileOwner(admin1);
2225
2226 setDeviceOwner();
2227 assertExpectException(SecurityException.class,
2228 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002229 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002230 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2231 clearDeviceOwner();
2232 }
2233
phweiss73145f42017-01-17 19:06:38 +01002234 public void testCreateAdminSupportIntent() throws Exception {
2235 // Setup device owner.
2236 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2237 setupDeviceOwner();
2238
2239 // Nonexisting permission returns null
2240 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2241 assertNull(intent);
2242
2243 // Existing permission that is not set returns null
2244 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2245 assertNull(intent);
2246
2247 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002248 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002249 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2250 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2251 .thenReturn(true);
2252 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2253 assertNull(intent);
2254
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002255 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2256 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2257 new UserManager.EnforcingUser(
2258 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2259 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002260 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002261 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002262 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2263 assertNotNull(intent);
2264 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2265 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2266 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002267 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002268 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2269 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2270
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002271 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2272 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002273
2274 // Camera is not disabled
2275 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2276 assertNull(intent);
2277
2278 // Camera is disabled
2279 dpm.setCameraDisabled(admin1, true);
2280 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2281 assertNotNull(intent);
2282 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2283 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2284
2285 // Screen capture is not disabled
2286 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2287 assertNull(intent);
2288
2289 // Screen capture is disabled
2290 dpm.setScreenCaptureDisabled(admin1, true);
2291 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2292 assertNotNull(intent);
2293 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2294 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2295
2296 // Same checks for different user
2297 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2298 // Camera should be disabled by device owner
2299 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2300 assertNotNull(intent);
2301 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2302 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2303 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2304 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2305 // ScreenCapture should not be disabled by device owner
2306 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2307 assertNull(intent);
2308 }
2309
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002310 /**
2311 * Test for:
2312 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002313 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002314 * {@link DevicePolicyManager#isAffiliatedUser}
2315 */
2316 public void testUserAffiliation() throws Exception {
2317 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2318 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2319 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2320
2321 // Check that the system user is unaffiliated.
2322 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2323 assertFalse(dpm.isAffiliatedUser());
2324
2325 // Set a device owner on the system user. Check that the system user becomes affiliated.
2326 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2327 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2328 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2329 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002330 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002331
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002332 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002333 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2334 setAsProfileOwner(admin2);
2335 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002336 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002337
2338 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2339 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002340 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002341 userAffiliationIds.add("red");
2342 userAffiliationIds.add("green");
2343 userAffiliationIds.add("blue");
2344 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002345 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002346 assertFalse(dpm.isAffiliatedUser());
2347
2348 // Have the device owner specify a set of affiliation ids that do not intersect with those
2349 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002350 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002351 deviceAffiliationIds.add("cyan");
2352 deviceAffiliationIds.add("yellow");
2353 deviceAffiliationIds.add("magenta");
2354 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2355 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002356 MoreAsserts.assertContentsInAnyOrder(
2357 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002358 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2359 assertFalse(dpm.isAffiliatedUser());
2360
2361 // Have the profile owner specify a set of affiliation ids that intersect with those
2362 // specified by the device owner. Check that the test user becomes affiliated.
2363 userAffiliationIds.add("yellow");
2364 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002365 MoreAsserts.assertContentsInAnyOrder(
2366 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002367 assertTrue(dpm.isAffiliatedUser());
2368
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002369 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002370 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002371 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002372 assertFalse(dpm.isAffiliatedUser());
2373
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002374 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2375 dpm.setAffiliationIds(admin2, userAffiliationIds);
2376 assertTrue(dpm.isAffiliatedUser());
2377 dpm.clearProfileOwner(admin2);
2378 assertFalse(dpm.isAffiliatedUser());
2379
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002380 // Check that the system user remains affiliated.
2381 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2382 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002383
2384 // Clear the device owner - the user becomes unaffiliated.
2385 clearDeviceOwner();
2386 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002387 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002388
2389 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002390 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002391 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2392 }
2393
2394 public void testSetUserProvisioningState_permission() throws Exception {
2395 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002396
2397 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2398 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2399 }
2400
2401 public void testSetUserProvisioningState_unprivileged() throws Exception {
2402 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002403 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2404 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2405 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002406 }
2407
2408 public void testSetUserProvisioningState_noManagement() {
2409 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002410 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002411 assertExpectException(IllegalStateException.class,
2412 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2413 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2414 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002415 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2416 }
2417
2418 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2419 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2420 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002421
2422 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2423 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2424 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2425 }
2426
2427 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2428 throws Exception {
2429 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2430 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002431
2432 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2433 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2434 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2435 }
2436
2437 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2438 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2439 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002440
2441 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2442 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2443 }
2444
2445 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2446 throws Exception {
2447 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002448
2449 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2450 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2451 DevicePolicyManager.STATE_USER_UNMANAGED);
2452 }
2453
2454 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2455 throws Exception {
2456 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002457
2458 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2459 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2460 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2461 }
2462
2463 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2464 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002465
2466 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2467 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2468 }
2469
2470 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2471 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002472
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002473 assertExpectException(IllegalStateException.class,
2474 /* messageRegex= */ "Cannot move to user provisioning state",
2475 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2476 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2477 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002478 }
2479
2480 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2481 throws Exception {
2482 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002483
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002484 assertExpectException(IllegalStateException.class,
2485 /* messageRegex= */ "Cannot move to user provisioning state",
2486 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2487 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2488 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002489 }
2490
2491 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002492 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2493 mContext.callerPermissions.add(permission.MANAGE_USERS);
2494
Alan Treadwayafad8782016-01-19 15:15:08 +00002495 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2496 for (int state : states) {
2497 dpm.setUserProvisioningState(state, userId);
2498 assertEquals(state, dpm.getUserProvisioningState());
2499 }
2500 }
2501
2502 private void setupProfileOwner() throws Exception {
2503 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2504
2505 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2506 dpm.setActiveAdmin(admin1, false);
2507 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2508
2509 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2510 }
2511
2512 private void setupDeviceOwner() throws Exception {
2513 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2514
2515 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2516 dpm.setActiveAdmin(admin1, false);
2517 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2518
2519 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2520 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002521
2522 public void testSetMaximumTimeToLock() {
2523 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2524
2525 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2526 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2527
Pavel Grafov75c0a892017-05-18 17:28:27 +01002528 reset(getServices().powerManagerInternal);
2529 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002530
2531 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002532 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2533 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002534 reset(getServices().powerManagerInternal);
2535 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002536
2537 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002538 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2539 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002540 reset(getServices().powerManagerInternal);
2541 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002542
2543 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002544 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2545 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002546 reset(getServices().powerManagerInternal);
2547 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002548
2549 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002550 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2551 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002552 reset(getServices().powerManagerInternal);
2553 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002554
2555 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002556 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2557 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002558 reset(getServices().powerManagerInternal);
2559 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002560
2561 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002562 reset(getServices().powerManagerInternal);
2563 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002564
Pavel Grafov28939982017-10-03 15:11:52 +01002565 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2566 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2567 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002568 reset(getServices().powerManagerInternal);
2569 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002570
2571 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002572 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2573 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002574 reset(getServices().powerManagerInternal);
2575 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002576
Pavel Grafov28939982017-10-03 15:11:52 +01002577 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002578 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002579 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2580 verifyStayOnWhilePluggedCleared(false);
2581 }
2582
2583 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2584 // uses separate challenge.
2585 public void testSetMaximumTimeToLockProfile() throws Exception {
2586 final int PROFILE_USER = 15;
2587 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2588 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2589 mContext.binder.callingUid = PROFILE_ADMIN;
2590 final DevicePolicyManagerInternal dpmi =
2591 LocalServices.getService(DevicePolicyManagerInternal.class);
2592
2593 dpm.setMaximumTimeToLock(admin1, 0);
2594
2595 reset(getServices().powerManagerInternal);
2596 reset(getServices().settings);
2597
2598 // First add timeout for the profile.
2599 dpm.setMaximumTimeToLock(admin1, 10);
2600 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2601
2602 reset(getServices().powerManagerInternal);
2603 reset(getServices().settings);
2604
2605 // Add separate challenge
2606 when(getServices().lockPatternUtils
2607 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2608 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2609
2610 verifyScreenTimeoutCall(10L, PROFILE_USER);
2611 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2612
2613 reset(getServices().powerManagerInternal);
2614 reset(getServices().settings);
2615
2616 // Remove the timeout.
2617 dpm.setMaximumTimeToLock(admin1, 0);
2618 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2619 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2620
2621 reset(getServices().powerManagerInternal);
2622 reset(getServices().settings);
2623
2624 // Add it back.
2625 dpm.setMaximumTimeToLock(admin1, 10);
2626 verifyScreenTimeoutCall(10L, PROFILE_USER);
2627 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2628
2629 reset(getServices().powerManagerInternal);
2630 reset(getServices().settings);
2631
2632 // Remove separate challenge.
2633 reset(getServices().lockPatternUtils);
2634 when(getServices().lockPatternUtils
2635 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2636 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002637 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002638
2639 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2640 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2641
2642 reset(getServices().powerManagerInternal);
2643 reset(getServices().settings);
2644
2645 // Remove the timeout.
2646 dpm.setMaximumTimeToLock(admin1, 0);
2647 verifyScreenTimeoutCall(null, PROFILE_USER);
2648 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002649 }
2650
Michal Karpinski943aabd2016-10-06 11:09:25 +01002651 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2652 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2653 setupDeviceOwner();
2654 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2655
Michal Karpinskid084ca52017-01-18 15:54:18 +00002656 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2657 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2658 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2659 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2660 - ONE_MINUTE;
2661
2662 // verify that the minimum timeout cannot be modified on user builds (system property is
2663 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002664 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002665
2666 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2667 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2668 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2669
Pavel Grafov75c0a892017-05-18 17:28:27 +01002670 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002671
2672 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002673 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002674
Michal Karpinskid084ca52017-01-18 15:54:18 +00002675 // reset to default (0 means the admin is not participating, so default should be returned)
2676 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002677
2678 // aggregation should be the default if unset by any admin
2679 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2680 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2681
2682 // admin not participating by default
2683 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2684
2685 //clamping from the top
2686 dpm.setRequiredStrongAuthTimeout(admin1,
2687 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2688 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2689 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2690 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2691 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2692
Michal Karpinskid084ca52017-01-18 15:54:18 +00002693 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002694 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2696 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2697 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2698
2699 // clamping from the bottom
2700 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2701 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2702 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2703
Michal Karpinskid084ca52017-01-18 15:54:18 +00002704 // values within range
2705 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2706 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2707 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2708
2709 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2710 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2711 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002712
2713 // reset to default
2714 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2715 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2716 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2717 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2718
2719 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002720 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2721 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002722 }
2723
Pavel Grafov28939982017-10-03 15:11:52 +01002724 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002725 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002726 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002727 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002728 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002729 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002730 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002731 }
Pavel Grafov28939982017-10-03 15:11:52 +01002732 }
2733
2734 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002735 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2736 // UnfinishedVerificationException.
2737 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002738
Esteban Talavera01576862016-12-15 11:16:44 +00002739 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002740 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002741 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002742 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002743 .thenReturn(false);
2744 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002745 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2746 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002747 .thenReturn(true);
2748 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2749
2750 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002751 }
Victor Chang3e794af2016-03-04 13:48:17 +00002752
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002753 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2754 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002755 mContext.packageName = admin1.getPackageName();
2756 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002757 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2758 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2759 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2760 false);
2761 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2762 }
2763
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002764 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2765 setup_DeviceAdminFeatureOff();
2766 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2767 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2768 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2769 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2770 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2771 assertCheckProvisioningPreCondition(
2772 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2773 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2774 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2775 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2776 }
2777
Esteban Talavera01576862016-12-15 11:16:44 +00002778 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002779 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002780 .thenReturn(false);
2781 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002782 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2783 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002784 .thenReturn(true);
2785 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2786
2787 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002788 }
Victor Chang3e794af2016-03-04 13:48:17 +00002789
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002790 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2791 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002792 mContext.packageName = admin1.getPackageName();
2793 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002794 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2795 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2796 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2797 false);
2798 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2799
2800 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002801 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002802 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2803 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2804 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2805 true);
2806 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2807 }
2808
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002809 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2810 setup_ManagedProfileFeatureOff();
2811 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2812 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2813 DevicePolicyManager.CODE_OK);
2814 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2815 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2816 assertCheckProvisioningPreCondition(
2817 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2818 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2819 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2820 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2821
2822 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002823 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002824 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2825 DevicePolicyManager.CODE_OK);
2826 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2827 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2828 assertCheckProvisioningPreCondition(
2829 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2830 DevicePolicyManager.CODE_OK);
2831 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2832 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2833 }
2834
Esteban Talavera01576862016-12-15 11:16:44 +00002835 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002836 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002837 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002838 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2839 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002840 .thenReturn(true);
2841 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2842
2843 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002844 }
Victor Chang3e794af2016-03-04 13:48:17 +00002845
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002846 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2847 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002848 mContext.packageName = admin1.getPackageName();
2849 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002850 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2851 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2852 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2853 false /* because of non-split user */);
2854 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2855 false /* because of non-split user */);
2856 }
2857
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002858 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002859 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002860 setup_nonSplitUser_firstBoot_primaryUser();
2861 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2862 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2863 DevicePolicyManager.CODE_OK);
2864 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2865 DevicePolicyManager.CODE_OK);
2866 assertCheckProvisioningPreCondition(
2867 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2868 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2869 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2870 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2871 }
2872
Esteban Talavera01576862016-12-15 11:16:44 +00002873 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002874 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002875 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002876 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2877 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002878 .thenReturn(true);
2879 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2880
2881 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002882 }
Victor Chang3e794af2016-03-04 13:48:17 +00002883
Nicolas Prevot45d29072017-01-18 16:11:19 +00002884 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2885 setDeviceOwner();
2886 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2887 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2888 }
2889
2890 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2891 setup_nonSplitUser_withDo_primaryUser();
2892 final int MANAGED_PROFILE_USER_ID = 18;
2893 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2894 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002895 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002896 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002897 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002898 true)).thenReturn(true);
2899 }
2900
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002901 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2902 throws Exception {
2903 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002904 mContext.packageName = admin1.getPackageName();
2905 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002906 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2907 false/* because of completed device setup */);
2908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2909 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2910 false/* because of non-split user */);
2911 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2912 false/* because of non-split user */);
2913 }
2914
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002915 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2916 throws Exception {
2917 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2918 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2919 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2920 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2921 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2922 DevicePolicyManager.CODE_OK);
2923 assertCheckProvisioningPreCondition(
2924 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2925 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2926 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2927 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2928 }
2929
Nicolas Prevot45d29072017-01-18 16:11:19 +00002930 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2931 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002932 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002933 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2934
2935 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2936 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002938
2939 // COMP mode is allowed.
2940 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2941 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002942 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002943
Nicolas Prevot45d29072017-01-18 16:11:19 +00002944 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002945 assertCheckProvisioningPreCondition(
2946 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002947 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002948 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002949 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2950 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2951 }
Esteban Talavera01576862016-12-15 11:16:44 +00002952
Nicolas Prevot45d29072017-01-18 16:11:19 +00002953 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2954 setup_nonSplitUser_withDo_primaryUser();
2955 mContext.packageName = admin1.getPackageName();
2956 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2957 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2958 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002959 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002960 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2961 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2962 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002963 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002964 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2965 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2966 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2967 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2968 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002969 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002970 assertCheckProvisioningPreCondition(
2971 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002972 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002973 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002974 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2975 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2976 }
Esteban Talavera01576862016-12-15 11:16:44 +00002977
Nicolas Prevot45d29072017-01-18 16:11:19 +00002978 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2979 throws Exception {
2980 setup_nonSplitUser_withDo_primaryUser();
2981 mContext.packageName = admin1.getPackageName();
2982 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002983 // The DO should not be allowed to initiate provisioning if the restriction is set by
2984 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002986 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2987 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2988 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002989 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002990 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2991 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2992 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2993 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2994 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002995 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2996
2997 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002998 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002999 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003000 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003001 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3002 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3003 }
3004
3005 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3006 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3007 mContext.packageName = admin1.getPackageName();
3008 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3009
3010 // We can delete the managed profile to create a new one, so provisioning is allowed.
3011 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3012 DevicePolicyManager.CODE_OK);
3013 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3014 assertCheckProvisioningPreCondition(
3015 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3016 DpmMockContext.ANOTHER_PACKAGE_NAME,
3017 DevicePolicyManager.CODE_OK);
3018 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3019 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3020 }
3021
3022 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3023 throws Exception {
3024 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3025 mContext.packageName = admin1.getPackageName();
3026 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003027 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003028 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3029 eq(UserHandle.SYSTEM)))
3030 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003031 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003032 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3033 eq(UserHandle.SYSTEM)))
3034 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003035
3036 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003037 assertCheckProvisioningPreCondition(
3038 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3039 DpmMockContext.ANOTHER_PACKAGE_NAME,
3040 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3041 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3042 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003043
3044 // But the device owner can still do it because it has set the restriction itself.
3045 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3046 DevicePolicyManager.CODE_OK);
3047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003048 }
3049
3050 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003051 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003052 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003053 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3054 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003055 .thenReturn(false);
3056 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3057
3058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 }
Victor Chang3e794af2016-03-04 13:48:17 +00003060
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3062 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003063 mContext.packageName = admin1.getPackageName();
3064 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3067 false /* because canAddMoreManagedProfiles returns false */);
3068 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3069 true);
3070 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3071 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003072 }
3073
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003074 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3075 throws Exception {
3076 setup_splitUser_firstBoot_systemUser();
3077 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3078 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3079 DevicePolicyManager.CODE_OK);
3080 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003081 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003082 assertCheckProvisioningPreCondition(
3083 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3084 DevicePolicyManager.CODE_OK);
3085 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3086 DevicePolicyManager.CODE_SYSTEM_USER);
3087 }
3088
Esteban Talavera01576862016-12-15 11:16:44 +00003089 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003090 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003091 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003092 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3093 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003094 .thenReturn(false);
3095 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3096
3097 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003098 }
Victor Chang3e794af2016-03-04 13:48:17 +00003099
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003100 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3101 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003102 mContext.packageName = admin1.getPackageName();
3103 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003104 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3105 true/* it's undefined behavior. Can be changed into false in the future */);
3106 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3107 false /* because canAddMoreManagedProfiles returns false */);
3108 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3109 true/* it's undefined behavior. Can be changed into false in the future */);
3110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3111 false/* because calling uid is system user */);
3112 }
3113
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003114 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3115 throws Exception {
3116 setup_splitUser_afterDeviceSetup_systemUser();
3117 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3118 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3119 DevicePolicyManager.CODE_OK);
3120 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003121 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003122 assertCheckProvisioningPreCondition(
3123 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3124 DevicePolicyManager.CODE_OK);
3125 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3126 DevicePolicyManager.CODE_SYSTEM_USER);
3127 }
3128
Esteban Talavera01576862016-12-15 11:16:44 +00003129 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003130 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003131 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003132 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3133 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003134 true)).thenReturn(true);
3135 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3136
3137 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003138 }
Victor Chang3e794af2016-03-04 13:48:17 +00003139
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003140 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3141 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003142 mContext.packageName = admin1.getPackageName();
3143 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3145 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3146 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3147 true);
3148 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003149 }
3150
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003151 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003152 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003153 setup_splitUser_firstBoot_primaryUser();
3154 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3155 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3156 DevicePolicyManager.CODE_OK);
3157 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3158 DevicePolicyManager.CODE_OK);
3159 assertCheckProvisioningPreCondition(
3160 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3161 DevicePolicyManager.CODE_OK);
3162 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3163 DevicePolicyManager.CODE_OK);
3164 }
3165
Esteban Talavera01576862016-12-15 11:16:44 +00003166 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003167 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003168 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003169 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3170 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003171 true)).thenReturn(true);
3172 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3173
3174 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003175 }
Victor Chang3e794af2016-03-04 13:48:17 +00003176
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003177 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3178 throws Exception {
3179 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003180 mContext.packageName = admin1.getPackageName();
3181 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003182 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3183 true/* it's undefined behavior. Can be changed into false in the future */);
3184 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3185 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3186 true/* it's undefined behavior. Can be changed into false in the future */);
3187 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3188 false/* because user setup completed */);
3189 }
3190
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003191 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003192 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003193 setup_splitUser_afterDeviceSetup_primaryUser();
3194 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3195 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3196 DevicePolicyManager.CODE_OK);
3197 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3198 DevicePolicyManager.CODE_OK);
3199 assertCheckProvisioningPreCondition(
3200 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3201 DevicePolicyManager.CODE_OK);
3202 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3203 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3204 }
3205
Esteban Talavera01576862016-12-15 11:16:44 +00003206 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003207 setDeviceOwner();
3208
Pavel Grafov75c0a892017-05-18 17:28:27 +01003209 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003210 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003211 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3212 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003213 .thenReturn(false);
3214 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3215
3216 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003217 }
Victor Chang3e794af2016-03-04 13:48:17 +00003218
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003219 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3220 throws Exception {
3221 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003222 mContext.packageName = admin1.getPackageName();
3223 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003224 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3225 false /* can't provision managed profile on system user */);
3226 }
3227
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003228 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003229 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003230 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3231 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3232 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3233 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3234 }
3235
3236 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003237 setDeviceOwner();
3238
Pavel Grafov75c0a892017-05-18 17:28:27 +01003239 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003240 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003241 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3242 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003243 true)).thenReturn(true);
3244 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3245
3246 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003247 }
Victor Chang3e794af2016-03-04 13:48:17 +00003248
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003249 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3250 throws Exception {
3251 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003252 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3253 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003254 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3255 }
3256
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003257 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003258 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003259 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003261
3262 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3264 DevicePolicyManager.CODE_OK);
3265 }
3266
3267 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003268 setDeviceOwner();
3269
Pavel Grafov75c0a892017-05-18 17:28:27 +01003270 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003271 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003272 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3273 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003274 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3275 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003276 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003277 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003278 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003279 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003280 true)).thenReturn(true);
3281 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3282
3283 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003284 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003285
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003286 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3287 throws Exception {
3288 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003289 mContext.packageName = admin1.getPackageName();
3290 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003291 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3292 }
3293
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3295 throws Exception {
3296 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3297 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3298 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3299 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3300 }
3301
3302 public void testCheckProvisioningPreCondition_permission() {
3303 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003304 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3305 () -> dpm.checkProvisioningPreCondition(
3306 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003307 }
3308
Victor Chang3577ed22016-08-25 18:49:26 +01003309 public void testForceUpdateUserSetupComplete_permission() {
3310 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003311 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3312 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003313 }
3314
3315 public void testForceUpdateUserSetupComplete_systemUser() {
3316 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3317 // GIVEN calling from user 20
3318 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003319 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3320 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003321 }
3322
3323 public void testForceUpdateUserSetupComplete_userbuild() {
3324 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3325 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3326
3327 final int userId = UserHandle.USER_SYSTEM;
3328 // GIVEN userComplete is false in SettingsProvider
3329 setUserSetupCompleteForUser(false, userId);
3330
3331 // GIVEN userComplete is true in DPM
3332 DevicePolicyManagerService.DevicePolicyData userData =
3333 new DevicePolicyManagerService.DevicePolicyData(userId);
3334 userData.mUserSetupComplete = true;
3335 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3336
3337 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003338 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003339
3340 assertTrue(dpms.hasUserSetupCompleted());
3341
3342 dpm.forceUpdateUserSetupComplete();
3343
3344 // THEN the state in dpms is not changed
3345 assertTrue(dpms.hasUserSetupCompleted());
3346 }
3347
3348 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3349 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3350 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3351
3352 final int userId = UserHandle.USER_SYSTEM;
3353 // GIVEN userComplete is false in SettingsProvider
3354 setUserSetupCompleteForUser(false, userId);
3355
3356 // GIVEN userComplete is true in DPM
3357 DevicePolicyManagerService.DevicePolicyData userData =
3358 new DevicePolicyManagerService.DevicePolicyData(userId);
3359 userData.mUserSetupComplete = true;
3360 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3361
3362 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003363 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003364
3365 assertTrue(dpms.hasUserSetupCompleted());
3366
3367 dpm.forceUpdateUserSetupComplete();
3368
3369 // THEN the state in dpms is not changed
3370 assertFalse(dpms.hasUserSetupCompleted());
3371 }
3372
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003373 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003374 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003375 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003376
3377 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3378 runAsCaller(mAdmin1Context, dpms, dpm -> {
3379 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3380 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003381 }
3382
3383 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3384 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3385 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003386
3387 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3388 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003389 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003390 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3391 .thenReturn(true);
3392
3393 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003394 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003395
3396 // Enabling logging should not change the timestamp.
3397 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003398 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003399 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003400 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003401 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003402 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003403
3404 // Retrieving the logs should update the timestamp.
3405 final long beforeRetrieval = System.currentTimeMillis();
3406 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003407 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003408 final long afterRetrieval = System.currentTimeMillis();
3409 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3410 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3411
3412 // Retrieving the pre-boot logs should update the timestamp.
3413 Thread.sleep(2);
3414 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003415 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003416 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3417
3418 // Checking the timestamp again should not change it.
3419 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003420 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003421
3422 // Retrieving the logs again should update the timestamp.
3423 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003424 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003425 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3426
3427 // Disabling logging should not change the timestamp.
3428 Thread.sleep(2);
3429 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003430 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003431
3432 // Restarting the DPMS should not lose the timestamp.
3433 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003434 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003435
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003436 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3437 mContext.binder.callingUid = 1234567;
3438 mContext.callerPermissions.add(permission.MANAGE_USERS);
3439 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3440 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3441
3442 // System can retrieve the timestamp.
3443 mContext.binder.clearCallingIdentity();
3444 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3445
3446 // Removing the device owner should clear the timestamp.
3447 clearDeviceOwner();
3448 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003449 }
3450
yuemingw0de748d2017-11-15 19:22:27 +00003451 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3452 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3453 setupDeviceOwner();
3454 assertExpectException(SecurityException.class, null, () ->
3455 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3456 }
3457
yuemingwc0281f12018-03-28 15:58:49 +01003458 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003459 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3460 setupDeviceOwner();
3461 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003462 verify(getServices().settings).settingsSystemPutStringForUser(
3463 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3464 }
3465
3466 public void testSetSystemSettingWithPO() throws Exception {
3467 setupProfileOwner();
3468 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3469 verify(getServices().settings).settingsSystemPutStringForUser(
3470 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003471 }
3472
yuemingwe43cdf72017-10-12 16:52:11 +01003473 public void testSetTime() throws Exception {
3474 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3475 setupDeviceOwner();
3476 dpm.setTime(admin1, 0);
3477 verify(getServices().alarmManager).setTime(0);
3478 }
3479
3480 public void testSetTimeFailWithPO() throws Exception {
3481 setupProfileOwner();
3482 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3483 }
3484
3485 public void testSetTimeWithAutoTimeOn() throws Exception {
3486 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3487 setupDeviceOwner();
3488 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3489 .thenReturn(1);
3490 assertFalse(dpm.setTime(admin1, 0));
3491 }
3492
3493 public void testSetTimeZone() throws Exception {
3494 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3495 setupDeviceOwner();
3496 dpm.setTimeZone(admin1, "Asia/Shanghai");
3497 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3498 }
3499
3500 public void testSetTimeZoneFailWithPO() throws Exception {
3501 setupProfileOwner();
3502 assertExpectException(SecurityException.class, null,
3503 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3504 }
3505
3506 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3507 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3508 setupDeviceOwner();
3509 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3510 .thenReturn(1);
3511 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3512 }
3513
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003514 public void testGetLastBugReportRequestTime() throws Exception {
3515 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3516 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003517
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518 mContext.packageName = admin1.getPackageName();
3519 mContext.applicationInfo = new ApplicationInfo();
3520 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3521 .thenReturn(Color.WHITE);
3522 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3523 anyObject())).thenReturn(Color.WHITE);
3524
Esteban Talaverad36dd152016-12-15 08:51:45 +00003525 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3526 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003527 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003528
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003529 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003530 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003531
3532 // Requesting a bug report should update the timestamp.
3533 final long beforeRequest = System.currentTimeMillis();
3534 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003535 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003536 final long afterRequest = System.currentTimeMillis();
3537 assertTrue(bugReportRequestTime >= beforeRequest);
3538 assertTrue(bugReportRequestTime <= afterRequest);
3539
3540 // Checking the timestamp again should not change it.
3541 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003542 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003543
3544 // Restarting the DPMS should not lose the timestamp.
3545 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003546 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003547
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003548 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3549 mContext.binder.callingUid = 1234567;
3550 mContext.callerPermissions.add(permission.MANAGE_USERS);
3551 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3552 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3553
3554 // System can retrieve the timestamp.
3555 mContext.binder.clearCallingIdentity();
3556 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3557
3558 // Removing the device owner should clear the timestamp.
3559 clearDeviceOwner();
3560 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003561 }
3562
3563 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3564 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3565 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003566 mContext.packageName = admin1.getPackageName();
3567 mContext.applicationInfo = new ApplicationInfo();
3568 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3569 .thenReturn(Color.WHITE);
3570 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3571 anyObject())).thenReturn(Color.WHITE);
3572
3573 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3574 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003575 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003576 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003577 .thenReturn(true);
3578
3579 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003580 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003581
3582 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3583 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003584 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003585
3586 // Enabling logging should not change the timestamp.
3587 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003588 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003589
3590 // Retrieving the logs should update the timestamp.
3591 final long beforeRetrieval = System.currentTimeMillis();
3592 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003593 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003594 final long afterRetrieval = System.currentTimeMillis();
3595 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3596 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3597
3598 // Checking the timestamp again should not change it.
3599 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003600 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003601
3602 // Retrieving the logs again should update the timestamp.
3603 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003604 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003605 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3606
3607 // Disabling logging should not change the timestamp.
3608 Thread.sleep(2);
3609 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003610 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003611
3612 // Restarting the DPMS should not lose the timestamp.
3613 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003614 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3615
3616 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3617 mContext.binder.callingUid = 1234567;
3618 mContext.callerPermissions.add(permission.MANAGE_USERS);
3619 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3620 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3621
3622 // System can retrieve the timestamp.
3623 mContext.binder.clearCallingIdentity();
3624 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3625
3626 // Removing the device owner should clear the timestamp.
3627 clearDeviceOwner();
3628 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003629 }
3630
Tony Mak2f26b792016-11-28 17:54:51 +00003631 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3632 // Setup device owner.
3633 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3634 setupDeviceOwner();
3635
3636 // Only device owner is setup, the result list should be empty.
3637 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3638 MoreAsserts.assertEmpty(targetUsers);
3639
3640 // Setup a managed profile managed by the same admin.
3641 final int MANAGED_PROFILE_USER_ID = 15;
3642 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3643 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3644
3645 // Add a secondary user, it should never talk with.
3646 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003647 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003648
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003649 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3650 // other.
3651 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3652 MoreAsserts.assertEmpty(targetUsers);
3653
3654 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3655 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3656 MoreAsserts.assertEmpty(targetUsers);
3657
3658 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003659 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003660 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3661 dpm.setAffiliationIds(admin1, userAffiliationIds);
3662
3663 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3664 dpm.setAffiliationIds(admin1, userAffiliationIds);
3665
Tony Mak2f26b792016-11-28 17:54:51 +00003666 // Calling from device owner admin, the result list should just contain the managed
3667 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003668 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003669 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3670 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3671
3672 // Calling from managed profile admin, the result list should just contain the system
3673 // user id.
3674 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3675 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3676 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003677
3678 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003679 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003680
3681 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3682 // to each other.
3683 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3684 MoreAsserts.assertEmpty(targetUsers);
3685
3686 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3687 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3688 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003689 }
3690
3691 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3692 // Setup a device owner.
3693 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3694 setupDeviceOwner();
3695
3696 // Set up a managed profile managed by different package.
3697 final int MANAGED_PROFILE_USER_ID = 15;
3698 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3699 final ComponentName adminDifferentPackage =
3700 new ComponentName("another.package", "whatever.class");
3701 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3702
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003703 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003704 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003705 dpm.setAffiliationIds(admin1, userAffiliationIds);
3706
3707 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3708 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3709
Tony Mak2f26b792016-11-28 17:54:51 +00003710 // Calling from device owner admin, we should get zero bind device admin target users as
3711 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003712 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003713 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3714 MoreAsserts.assertEmpty(targetUsers);
3715
3716 // Calling from managed profile admin, we should still get zero target users for the same
3717 // reason.
3718 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3719 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3720 MoreAsserts.assertEmpty(targetUsers);
3721 }
3722
Jason Parks3c13b642017-11-28 15:39:43 -06003723 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003724 verifyLockTaskState(userId, new String[0],
3725 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003726 }
3727
3728 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3729 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003730 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003731 }
3732
3733 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3734 int flags) throws Exception {
3735 mContext.binder.callingUid = uid;
3736 dpm.setLockTaskPackages(who, packages);
3737 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3738 for (String p : packages) {
3739 assertTrue(dpm.isLockTaskPermitted(p));
3740 }
3741 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3742 // Test to see if set lock task features can be set
3743 dpm.setLockTaskFeatures(who, flags);
3744 verifyLockTaskState(userId, packages, flags);
3745 }
3746
3747 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3748 int flags) throws Exception {
3749 mContext.binder.callingUid = uid;
3750 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3751 () -> dpm.setLockTaskPackages(who, packages));
3752 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3753 () -> dpm.getLockTaskPackages(who));
3754 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3755 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3756 () -> dpm.setLockTaskFeatures(who, flags));
3757 }
3758
Charles Hee078db72017-10-19 18:03:20 +01003759 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003760 // Setup a device owner.
3761 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3762 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003763 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003764 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003765
3766 // Set up a managed profile managed by different package (package name shouldn't matter)
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);
Jason Parks3c13b642017-11-28 15:39:43 -06003772 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3773
3774 // Setup a PO on the secondary user
3775 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3776 setAsProfileOwner(admin3);
3777 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003778
3779 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003780 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003781 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003782 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3783 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003784 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3785
3786 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3787 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003788 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3789 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003790 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003791
3792 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3793 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3794 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003795 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003796 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3797 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003798 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003799
3800 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003801 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003802 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3803 dpm.setAffiliationIds(admin1, userAffiliationIds);
3804
3805 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3806 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3807
3808 // Now the managed profile can set lock task packages.
3809 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3810 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3811 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3812 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003813 // And it can set lock task features.
3814 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003815 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003816
3817 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003818 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003819 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3820 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003821 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3822 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003823 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003824 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003825
Jason Parks3c13b642017-11-28 15:39:43 -06003826 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003827 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3828 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003829
3830 }
3831
3832 public void testLockTaskPolicyForProfileOwner() throws Exception {
3833 // Setup a PO
3834 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3835 setAsProfileOwner(admin1);
3836 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3837
3838 final String[] poPackages = {"poPackage1", "poPackage2"};
3839 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003840 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3841 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003842 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3843 poPackages, poFlags);
3844
3845 // Set up a managed profile managed by different package (package name shouldn't matter)
3846 final int MANAGED_PROFILE_USER_ID = 15;
3847 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3848 final ComponentName adminDifferentPackage =
3849 new ComponentName("another.package", "whatever.class");
3850 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3851 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3852
3853 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3854 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3855 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3856 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003857 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3858 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003859 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003860 }
3861
Benjamin Franzcaffa772018-02-05 16:36:10 +00003862 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3863 // Setup a device owner.
3864 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3865 setupDeviceOwner();
3866 // Lock task policy is updated when loading user data.
3867 verifyLockTaskState(UserHandle.USER_SYSTEM);
3868
3869 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3870 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3871 assertExpectException(IllegalArgumentException.class,
3872 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3873 () -> dpm.setLockTaskFeatures(admin1, flags));
3874 }
3875
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003876 public void testIsDeviceManaged() throws Exception {
3877 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3878 setupDeviceOwner();
3879
3880 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3881 // find out that the device has a device owner.
3882 assertTrue(dpm.isDeviceManaged());
3883 mContext.binder.callingUid = 1234567;
3884 mContext.callerPermissions.add(permission.MANAGE_USERS);
3885 assertTrue(dpm.isDeviceManaged());
3886 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3887 mContext.binder.clearCallingIdentity();
3888 assertTrue(dpm.isDeviceManaged());
3889
3890 clearDeviceOwner();
3891
3892 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3893 // not have a device owner.
3894 mContext.binder.callingUid = 1234567;
3895 mContext.callerPermissions.add(permission.MANAGE_USERS);
3896 assertFalse(dpm.isDeviceManaged());
3897 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3898 mContext.binder.clearCallingIdentity();
3899 assertFalse(dpm.isDeviceManaged());
3900 }
3901
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003902 public void testDeviceOwnerOrganizationName() throws Exception {
3903 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3904 setupDeviceOwner();
3905
3906 dpm.setOrganizationName(admin1, "organization");
3907
3908 // Device owner can retrieve organization managing the device.
3909 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3910
3911 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3912 mContext.binder.callingUid = 1234567;
3913 mContext.callerPermissions.add(permission.MANAGE_USERS);
3914 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3915 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3916
3917 // System can retrieve organization managing the device.
3918 mContext.binder.clearCallingIdentity();
3919 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3920
3921 // Removing the device owner clears the organization managing the device.
3922 clearDeviceOwner();
3923 assertNull(dpm.getDeviceOwnerOrganizationName());
3924 }
3925
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003926 public void testWipeDataManagedProfile() throws Exception {
3927 final int MANAGED_PROFILE_USER_ID = 15;
3928 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3929 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3930 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3931
3932 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003933 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003934 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003935 // Get mock reason string since we throw an IAE with empty string input.
3936 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3937 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003938
3939 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003940 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003941 MANAGED_PROFILE_USER_ID);
3942 }
3943
3944 public void testWipeDataManagedProfileDisallowed() throws Exception {
3945 final int MANAGED_PROFILE_USER_ID = 15;
3946 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3947 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3948
3949 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003950 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003951 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3952
Pavel Grafov75c0a892017-05-18 17:28:27 +01003953 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003954 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3955 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3956 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003957 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3958 thenReturn("Just a test string.");
3959
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003960 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003961 // The PO is not allowed to remove the profile if the user restriction was set on the
3962 // profile by the system
3963 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3964 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003965 }
3966
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003967 public void testWipeDataDeviceOwner() throws Exception {
3968 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003969 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003970 UserManager.DISALLOW_FACTORY_RESET,
3971 UserHandle.SYSTEM))
3972 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003973 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3974 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003975
3976 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003977 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003978 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3979 /*wipeEuicc=*/ eq(false));
3980 }
3981
3982 public void testWipeEuiccDataEnabled() throws Exception {
3983 setDeviceOwner();
3984 when(getServices().userManager.getUserRestrictionSource(
3985 UserManager.DISALLOW_FACTORY_RESET,
3986 UserHandle.SYSTEM))
3987 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003988 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3989 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003990
3991 dpm.wipeData(WIPE_EUICC);
3992 verify(getServices().recoverySystem).rebootWipeUserData(
3993 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3994 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003995 }
3996
3997 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3998 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003999 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004000 UserManager.DISALLOW_FACTORY_RESET,
4001 UserHandle.SYSTEM))
4002 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004003 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4004 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004005 // The DO is not allowed to wipe the device if the user restriction was set
4006 // by the system
4007 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4008 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004009 }
4010
4011 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4012 final int MANAGED_PROFILE_USER_ID = 15;
4013 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4014 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4015
4016 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004017 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004018 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4019
Pavel Grafov75c0a892017-05-18 17:28:27 +01004020 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004021 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4022 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4023 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4024
4025 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4026 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4027
4028 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4029 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4030 // Failed password attempts on the parent user are taken into account, as there isn't a
4031 // separate work challenge.
4032 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4033 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4034 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4035
4036 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4037 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004038 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004039 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004040 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004041 }
4042
4043 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4044 throws Exception {
4045 final int MANAGED_PROFILE_USER_ID = 15;
4046 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4047 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4048
4049 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004050 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004051 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4052
Pavel Grafov75c0a892017-05-18 17:28:27 +01004053 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004054 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4055 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4056 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4057
4058 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4059 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4060
4061 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4062 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4063 // Failed password attempts on the parent user are taken into account, as there isn't a
4064 // separate work challenge.
4065 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4066 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4067 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4068
4069 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4070 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004071 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004072 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004073 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004074 }
4075
4076 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4077 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004078 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004079 UserManager.DISALLOW_FACTORY_RESET,
4080 UserHandle.SYSTEM))
4081 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4082
4083 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4084
4085 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4086 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4087 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4088 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4089 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4090
4091 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4092 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004093 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004094 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4095 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004096 }
4097
4098 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4099 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004100 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004101 UserManager.DISALLOW_FACTORY_RESET,
4102 UserHandle.SYSTEM))
4103 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4104
4105 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4106
4107 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4108 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4109 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4110 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4111 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4112
4113 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004114 verifyZeroInteractions(getServices().recoverySystem);
4115 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004116 .removeUserEvenWhenDisallowed(anyInt());
4117 }
4118
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004119 public void testGetPermissionGrantState() throws Exception {
4120 final String permission = "some.permission";
4121 final String app1 = "com.example.app1";
4122 final String app2 = "com.example.app2";
4123
Pavel Grafov75c0a892017-05-18 17:28:27 +01004124 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004125 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004126 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004127 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004128 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004129 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4130 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004131 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004132 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004133 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004134 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004135 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004136 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4137
4138 // System can retrieve permission grant state.
4139 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004140 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004141 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4142 dpm.getPermissionGrantState(null, app1, permission));
4143 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4144 dpm.getPermissionGrantState(null, app2, permission));
4145
4146 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004147 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4148 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004149 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4150 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004151
4152 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004153 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4154 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004155 setAsProfileOwner(admin1);
4156 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4157 dpm.getPermissionGrantState(admin1, app1, permission));
4158 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4159 dpm.getPermissionGrantState(admin1, app2, permission));
4160 }
4161
Rubin Xuaab7a412016-12-30 21:13:29 +00004162 public void testResetPasswordWithToken() throws Exception {
4163 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4164 setupDeviceOwner();
4165 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004166 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4167 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4168
Rubin Xuaab7a412016-12-30 21:13:29 +00004169 // test adding a token
4170 final byte[] token = new byte[32];
4171 final long handle = 123456;
4172 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004173 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4174 nullable(EscrowTokenStateChangeCallback.class)))
4175 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004176 assertTrue(dpm.setResetPasswordToken(admin1, token));
4177
4178 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004179 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004180 .thenReturn(true);
4181 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4182
4183 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004184 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004185 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004186 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004187 eq(UserHandle.USER_SYSTEM)))
4188 .thenReturn(true);
4189 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4190
4191 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004192 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004193 .thenReturn(true);
4194 assertTrue(dpm.clearResetPasswordToken(admin1));
4195 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004196
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004197 public void testIsActivePasswordSufficient() throws Exception {
4198 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4199 mContext.packageName = admin1.getPackageName();
4200 setupDeviceOwner();
4201
4202 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4203 dpm.setPasswordMinimumLength(admin1, 8);
4204 dpm.setPasswordMinimumLetters(admin1, 6);
4205 dpm.setPasswordMinimumLowerCase(admin1, 3);
4206 dpm.setPasswordMinimumUpperCase(admin1, 1);
4207 dpm.setPasswordMinimumNonLetter(admin1, 1);
4208 dpm.setPasswordMinimumNumeric(admin1, 1);
4209 dpm.setPasswordMinimumSymbols(admin1, 0);
4210
Rubin Xucc391c22018-01-02 20:37:35 +00004211 reset(mContext.spiedContext);
4212
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004213 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4214 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4215 8, 2,
4216 6, 1,
4217 0, 1);
4218
4219 setActivePasswordState(passwordMetricsNoSymbols);
4220 assertTrue(dpm.isActivePasswordSufficient());
4221
4222 initializeDpms();
4223 reset(mContext.spiedContext);
4224 assertTrue(dpm.isActivePasswordSufficient());
4225
4226 // This call simulates the user entering the password for the first time after a reboot.
4227 // This causes password metrics to be reloaded into memory. Until this happens,
4228 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4229 // even if the DPC changes password requirements so that the password no longer meets the
4230 // requirements. This is a known limitation of the current implementation of
4231 // isActivePasswordSufficient() - see b/34218769.
4232 setActivePasswordState(passwordMetricsNoSymbols);
4233 assertTrue(dpm.isActivePasswordSufficient());
4234
4235 dpm.setPasswordMinimumSymbols(admin1, 1);
4236 // This assertion would fail if we had not called setActivePasswordState() again after
4237 // initializeDpms() - see previous comment.
4238 assertFalse(dpm.isActivePasswordSufficient());
4239
4240 initializeDpms();
4241 reset(mContext.spiedContext);
4242 assertFalse(dpm.isActivePasswordSufficient());
4243
4244 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4245 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4246 7, 2,
4247 5, 1,
4248 1, 2);
4249
4250 setActivePasswordState(passwordMetricsWithSymbols);
4251 assertTrue(dpm.isActivePasswordSufficient());
4252 }
4253
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004254 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4255 // If there is no lock screen, the password is considered empty no matter what, because
4256 // it provides no security.
4257 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4258
4259 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4260 mContext.packageName = admin1.getPackageName();
4261 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004262 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4263 // When there is no lockscreen, user password metrics is always empty.
4264 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4265 .thenReturn(new PasswordMetrics());
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004266
4267 // If no password requirements are set, isActivePasswordSufficient should succeed.
4268 assertTrue(dpm.isActivePasswordSufficient());
4269
4270 // Now set some password quality requirements.
4271 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4272
4273 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004274 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004275 dpm.reportPasswordChanged(userHandle);
4276
4277 // No broadcast should be sent.
4278 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4279 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4280 MockUtils.checkUserHandle(userHandle));
4281
4282 // The active (nonexistent) password doesn't comply with the requirements.
4283 assertFalse(dpm.isActivePasswordSufficient());
4284 }
4285
Pavel Grafov75c0a892017-05-18 17:28:27 +01004286 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4287 throws Exception {
4288 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004289 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004290
Rubin Xu19854862019-08-15 16:37:23 +01004291 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4292 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004293 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004294
Rubin Xucc391c22018-01-02 20:37:35 +00004295 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4296 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004297 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004298 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4299 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004300 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004301 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4302 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004303 // userId, if the password checkpoint value changes.
4304 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4305 MockUtils.checkIntentAction(
4306 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4307 MockUtils.checkUserHandle(userHandle));
4308 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004309 MockUtils.checkIntentAction(
4310 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4311 MockUtils.checkUserHandle(userHandle));
4312
Pavel Grafov75c0a892017-05-18 17:28:27 +01004313 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4314 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004315 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004316
4317 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4318 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004319 MockUtils.checkUserHandle(userHandle),
4320 eq(null),
4321 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004322
4323 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4324 // let it finish with system uid, otherwise it will throw and crash.
4325 flushTasks();
4326
4327 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004328 }
4329
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004330 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4331 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4332 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4333 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4334 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4335 DpmMockContext.SYSTEM_UID);
4336 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4337 DpmMockContext.SYSTEM_UID);
4338
4339 // Set up a device owner.
4340 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004341 setupDeviceOwner();
4342
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004343 // First and second user set IMEs manually.
4344 mContext.binder.callingUid = firstUserSystemUid;
4345 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4346 mContext.binder.callingUid = secondUserSystemUid;
4347 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004348
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004349 // Device owner changes IME for first user.
4350 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004351 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004352 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004353 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004354 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004355 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004357 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4358 mContext.binder.callingUid = firstUserSystemUid;
4359 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4360 mContext.binder.callingUid = secondUserSystemUid;
4361 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004362
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004363 // Second user changes IME manually.
4364 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4365 mContext.binder.callingUid = firstUserSystemUid;
4366 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4367 mContext.binder.callingUid = secondUserSystemUid;
4368 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004369
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004370 // First user changes IME manually.
4371 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4372 mContext.binder.callingUid = firstUserSystemUid;
4373 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4374 mContext.binder.callingUid = secondUserSystemUid;
4375 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004376
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004377 // Device owner changes IME for first user again.
4378 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004379 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004380 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004382 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004383 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004384 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4385 mContext.binder.callingUid = firstUserSystemUid;
4386 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4387 mContext.binder.callingUid = secondUserSystemUid;
4388 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004389
4390 // Restarting the DPMS should not lose information.
4391 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004392 mContext.binder.callingUid = firstUserSystemUid;
4393 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4394 mContext.binder.callingUid = secondUserSystemUid;
4395 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004396
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004397 // Device owner can find out whether it set the current IME itself.
4398 mContext.binder.callingUid = deviceOwnerUid;
4399 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004400
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004402 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004403 mContext.binder.callingUid = firstUserSystemUid;
4404 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4405 mContext.binder.callingUid = secondUserSystemUid;
4406 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004407 }
4408
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004409 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4410 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4411 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4412 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4413 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4414 DpmMockContext.SYSTEM_UID);
4415 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4416 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004417
4418 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004419 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420 setupProfileOwner();
4421
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004422 // First and second user set IMEs manually.
4423 mContext.binder.callingUid = firstUserSystemUid;
4424 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4425 mContext.binder.callingUid = secondUserSystemUid;
4426 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 // Profile owner changes IME for second user.
4429 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004430 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004431 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004432 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004433 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004434 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004435 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004436 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4437 mContext.binder.callingUid = firstUserSystemUid;
4438 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4439 mContext.binder.callingUid = secondUserSystemUid;
4440 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004441
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004442 // First user changes IME manually.
4443 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4444 mContext.binder.callingUid = firstUserSystemUid;
4445 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4446 mContext.binder.callingUid = secondUserSystemUid;
4447 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004448
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004449 // Second user changes IME manually.
4450 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4451 mContext.binder.callingUid = firstUserSystemUid;
4452 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4453 mContext.binder.callingUid = secondUserSystemUid;
4454 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004455
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004456 // Profile owner changes IME for second user again.
4457 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004460 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004462 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004463 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4464 mContext.binder.callingUid = firstUserSystemUid;
4465 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4466 mContext.binder.callingUid = secondUserSystemUid;
4467 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004468
4469 // Restarting the DPMS should not lose information.
4470 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004471 mContext.binder.callingUid = firstUserSystemUid;
4472 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4473 mContext.binder.callingUid = secondUserSystemUid;
4474 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004475
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004476 // Profile owner can find out whether it set the current IME itself.
4477 mContext.binder.callingUid = profileOwnerUid;
4478 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004479
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004480 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004481 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004482 mContext.binder.callingUid = firstUserSystemUid;
4483 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4484 mContext.binder.callingUid = secondUserSystemUid;
4485 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004486 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004487
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004488 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4489 throws Exception {
4490 // Set up a device owner.
4491 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4492 setupDeviceOwner();
4493 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4494 }
4495
4496 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4497 throws Exception {
4498 // Set up a profile owner.
4499 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4500 setupProfileOwner();
4501 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4502 }
4503
4504 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4505 int adminUid) throws Exception {
4506 mContext.binder.callingUid = adminUid;
4507 final int userId = UserHandle.getUserId(adminUid);
4508
4509 final String packageName = "some.package";
4510 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4511 admin1, Collections.singletonList(packageName)));
4512 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4513
4514 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4515 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4516
4517 // Attempt to set to empty list (which means no listener is whitelisted)
4518 mContext.binder.callingUid = adminUid;
4519 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004520 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004521 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4522
4523 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4524 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4525 }
4526
4527 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4528 // Set up a managed profile
4529 final int MANAGED_PROFILE_USER_ID = 15;
4530 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4531 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4532 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4533
4534 final String permittedListener = "some.package";
4535 setupPackageInPackageManager(
4536 permittedListener,
4537 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4538 /*appId=*/ 12345, /*flags=*/ 0);
4539
4540 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4541 admin1, Collections.singletonList(permittedListener)));
4542
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004543 // isNotificationListenerServicePermitted should throw if not called from System.
4544 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4545 () -> dpms.isNotificationListenerServicePermitted(
4546 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004547
4548 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4549 assertTrue(dpms.isNotificationListenerServicePermitted(
4550 permittedListener, MANAGED_PROFILE_USER_ID));
4551 }
4552
4553 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4554 throws Exception {
4555 // Set up a managed profile
4556 final int MANAGED_PROFILE_USER_ID = 15;
4557 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4558 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4559 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4560
4561 final String permittedListener = "permitted.package";
4562 int appId = 12345;
4563 setupPackageInPackageManager(
4564 permittedListener,
4565 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4566 appId, /*flags=*/ 0);
4567
4568 final String notPermittedListener = "not.permitted.package";
4569 setupPackageInPackageManager(
4570 notPermittedListener,
4571 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4572 ++appId, /*flags=*/ 0);
4573
4574 final String systemListener = "system.package";
4575 setupPackageInPackageManager(
4576 systemListener,
4577 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4578 ++appId, ApplicationInfo.FLAG_SYSTEM);
4579
4580 // By default all packages are allowed
4581 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4582
4583 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4584 assertTrue(dpms.isNotificationListenerServicePermitted(
4585 permittedListener, MANAGED_PROFILE_USER_ID));
4586 assertTrue(dpms.isNotificationListenerServicePermitted(
4587 notPermittedListener, MANAGED_PROFILE_USER_ID));
4588 assertTrue(dpms.isNotificationListenerServicePermitted(
4589 systemListener, MANAGED_PROFILE_USER_ID));
4590
4591 // Setting only one package in the whitelist
4592 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4593 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4594 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004595 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004596 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4597 assertEquals(1, permittedListeners.size());
4598 assertEquals(permittedListener, permittedListeners.get(0));
4599
4600 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4601 assertTrue(dpms.isNotificationListenerServicePermitted(
4602 permittedListener, MANAGED_PROFILE_USER_ID));
4603 assertFalse(dpms.isNotificationListenerServicePermitted(
4604 notPermittedListener, MANAGED_PROFILE_USER_ID));
4605 // System packages are always allowed (even if not in the whitelist)
4606 assertTrue(dpms.isNotificationListenerServicePermitted(
4607 systemListener, MANAGED_PROFILE_USER_ID));
4608
4609 // Setting an empty whitelist - only system listeners allowed
4610 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4611 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004612 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004613 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4614
4615 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4616 assertFalse(dpms.isNotificationListenerServicePermitted(
4617 permittedListener, MANAGED_PROFILE_USER_ID));
4618 assertFalse(dpms.isNotificationListenerServicePermitted(
4619 notPermittedListener, MANAGED_PROFILE_USER_ID));
4620 // System packages are always allowed (even if not in the whitelist)
4621 assertTrue(dpms.isNotificationListenerServicePermitted(
4622 systemListener, MANAGED_PROFILE_USER_ID));
4623
4624 // Setting a null whitelist - all listeners allowed
4625 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4626 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4627 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4628
4629 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4630 assertTrue(dpms.isNotificationListenerServicePermitted(
4631 permittedListener, MANAGED_PROFILE_USER_ID));
4632 assertTrue(dpms.isNotificationListenerServicePermitted(
4633 notPermittedListener, MANAGED_PROFILE_USER_ID));
4634 assertTrue(dpms.isNotificationListenerServicePermitted(
4635 systemListener, MANAGED_PROFILE_USER_ID));
4636 }
4637
4638 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4639 throws Exception {
4640 // Set up a managed profile
4641 final int MANAGED_PROFILE_USER_ID = 15;
4642 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4643 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4644 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4645
4646 final String nonSystemPackage = "non.system.package";
4647 int appId = 12345;
4648 setupPackageInPackageManager(
4649 nonSystemPackage,
4650 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4651 appId, /*flags=*/ 0);
4652
4653 final String systemListener = "system.package";
4654 setupPackageInPackageManager(
4655 systemListener,
4656 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4657 ++appId, ApplicationInfo.FLAG_SYSTEM);
4658
4659 // By default all packages are allowed (for all profiles)
4660 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4661
4662 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4663 assertTrue(dpms.isNotificationListenerServicePermitted(
4664 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4665 assertTrue(dpms.isNotificationListenerServicePermitted(
4666 systemListener, MANAGED_PROFILE_USER_ID));
4667 assertTrue(dpms.isNotificationListenerServicePermitted(
4668 nonSystemPackage, UserHandle.USER_SYSTEM));
4669 assertTrue(dpms.isNotificationListenerServicePermitted(
4670 systemListener, UserHandle.USER_SYSTEM));
4671
4672 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4673 // all allowed in primary profile
4674 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4675 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004676 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004677 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4678
4679 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4680 assertFalse(dpms.isNotificationListenerServicePermitted(
4681 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4682 assertTrue(dpms.isNotificationListenerServicePermitted(
4683 systemListener, MANAGED_PROFILE_USER_ID));
4684 assertTrue(dpms.isNotificationListenerServicePermitted(
4685 nonSystemPackage, UserHandle.USER_SYSTEM));
4686 assertTrue(dpms.isNotificationListenerServicePermitted(
4687 systemListener, UserHandle.USER_SYSTEM));
4688 }
4689
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004690 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004691 mServiceContext.packageName = mRealTestContext.getPackageName();
4692 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4693 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004694 setDeviceOwner();
4695
Pavel Grafov75c0a892017-05-18 17:28:27 +01004696 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004697 }
4698
4699 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004700 mServiceContext.packageName = mRealTestContext.getPackageName();
4701 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4702 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004703 setAsProfileOwner(admin1);
4704
Pavel Grafov75c0a892017-05-18 17:28:27 +01004705 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4706 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004707 }
4708
4709 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004710 mServiceContext.packageName = mRealTestContext.getPackageName();
4711 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4712 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004713 setAsProfileOwner(admin1);
4714
Pavel Grafov75c0a892017-05-18 17:28:27 +01004715 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4716 caller.packageName = "com.example.delegate";
4717 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4718 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004719
Pavel Grafov75c0a892017-05-18 17:28:27 +01004720 // Make caller a delegated cert installer.
4721 runAsCaller(mAdmin1Context, dpms,
4722 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004723
4724 verifyCanGetOwnerInstalledCaCerts(null, caller);
4725 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004726 }
4727
Rubin Xucc391c22018-01-02 20:37:35 +00004728 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004729 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4730 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004731 Bundle restriction = new Bundle();
4732 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4733
4734 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4735 RestrictionsListener listener = new RestrictionsListener(mContext);
4736 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4737 new Bundle());
4738 verifyDataSharingChangedBroadcast();
4739 }
4740
4741 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004742 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4743 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004744 Bundle restriction = new Bundle();
4745 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4746
4747 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4748 RestrictionsListener listener = new RestrictionsListener(mContext);
4749 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4750 restriction);
4751 verifyDataSharingChangedBroadcast();
4752 }
4753
4754 public void testDisallowSharingIntoProfileUnchanged() {
4755 RestrictionsListener listener = new RestrictionsListener(mContext);
4756 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4757 new Bundle());
4758 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4759 }
4760
4761 private void verifyDataSharingChangedBroadcast() {
4762 Intent expectedIntent = new Intent(
4763 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4764 expectedIntent.setPackage("com.android.managedprovisioning");
4765 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4766 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4767 MockUtils.checkIntent(expectedIntent),
4768 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4769 }
4770
yuemingwe3d9c092018-01-11 12:11:44 +00004771 public void testOverrideApnAPIsFailWithPO() throws Exception {
4772 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004773 ApnSetting apn = (new ApnSetting.Builder())
4774 .setApnName("test")
4775 .setEntryName("test")
4776 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4777 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004778 assertExpectException(SecurityException.class, null, () ->
4779 dpm.addOverrideApn(admin1, apn));
4780 assertExpectException(SecurityException.class, null, () ->
4781 dpm.updateOverrideApn(admin1, 0, apn));
4782 assertExpectException(SecurityException.class, null, () ->
4783 dpm.removeOverrideApn(admin1, 0));
4784 assertExpectException(SecurityException.class, null, () ->
4785 dpm.getOverrideApns(admin1));
4786 assertExpectException(SecurityException.class, null, () ->
4787 dpm.setOverrideApnsEnabled(admin1, false));
4788 assertExpectException(SecurityException.class, null, () ->
4789 dpm.isOverrideApnEnabled(admin1));
4790 }
4791
Robin Lee2c68dad2017-03-17 12:50:24 +00004792 private void verifyCanGetOwnerInstalledCaCerts(
4793 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004794 final String alias = "cert";
4795 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004796
4797 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004798 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004799 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4800 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004801 }
4802 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4803
4804 // caller: device admin or delegated certificate installer
4805 callerContext.applicationInfo = new ApplicationInfo();
4806 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4807
4808 // system_server
4809 final DpmMockContext serviceContext = mContext;
4810 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004811 getServices().addPackageContext(callerUser, admin1Context);
4812 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004813
4814 // Install a CA cert.
4815 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004816 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004817 .thenReturn(alias);
4818 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004819 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004820 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004821 });
4822
Pavel Grafov75c0a892017-05-18 17:28:27 +01004823 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4824 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4825 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004826 flushTasks();
4827
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4829
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004830 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004831 runAsCaller(admin1Context, dpms, (dpm) -> {
4832 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004833 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004834 ownerInstalledCaCerts.addAll(installedCaCerts);
4835 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004836
4837 // Restarting the DPMS should not lose information.
4838 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004839 runAsCaller(admin1Context, dpms, (dpm) ->
4840 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004841
4842 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004843 runAsCaller(serviceContext, dpms, (dpm) -> {
4844 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004845
Robin Lee2c68dad2017-03-17 12:50:24 +00004846 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004847 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004848 });
4849
Pavel Grafov75c0a892017-05-18 17:28:27 +01004850 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4851 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4852 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004853 flushTasks();
4854
4855 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4856 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004857 runAsCaller(admin1Context, dpms, (dpm) -> {
4858 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4859 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004860 }
4861
Robin Lee2c68dad2017-03-17 12:50:24 +00004862 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4863 final ComponentName callerName, 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 as caller
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(callerName, caCert));
4889 });
4890
4891 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004892 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004893 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004894 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4895 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4896 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004897 flushTasks();
4898
Robin Lee2c68dad2017-03-17 12:50:24 +00004899 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004900 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004901
4902 runAsCaller(serviceContext, dpms, (dpm) -> {
4903 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4904 assertNotNull(ownerInstalledCaCerts);
4905 assertTrue(ownerInstalledCaCerts.isEmpty());
4906 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004907 }
4908
Eran Messeri94d56762017-12-21 20:50:54 +00004909 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4910 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4911 Arrays.sort(gotFlags);
4912 Arrays.sort(expectedFlags);
4913 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4914 }
4915
4916 public void testTranslationOfIdAttestationFlag() {
4917 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4918 int[] correspondingAttUtilsTypes = new int[]{
4919 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4920 AttestationUtils.ID_TYPE_MEID};
4921
4922 // Test translation of zero flags
4923 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4924
4925 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4926 // non-null array
4927 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4928
4929 // Test translation of a single flag
4930 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4931 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4932 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4933
4934 // Test translation of two flags
4935 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4936 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4937 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4938 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4939
4940 // Test translation of all three flags
4941 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4942 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4943 AttestationUtils.ID_TYPE_MEID});
4944 // Test translation of all three flags
4945 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4946 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4947 AttestationUtils.ID_TYPE_MEID});
4948 }
4949
arangelov08d534b2018-01-22 15:20:53 +00004950 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4951 setDeviceOwner();
4952 initializeDpms();
4953 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4954 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4955 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4956 }
4957
4958 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4959 DpmTestUtils.writeInputStreamToFile(
4960 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4961 getDeviceOwnerPoliciesFile());
4962 DpmTestUtils.writeInputStreamToFile(
4963 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4964 getDeviceOwnerFile());
4965 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4966 }
4967
4968 public void testRevertDeviceOwnership_deviceNotMigrated()
4969 throws Exception {
4970 DpmTestUtils.writeInputStreamToFile(
4971 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4972 getDeviceOwnerPoliciesFile());
4973 DpmTestUtils.writeInputStreamToFile(
4974 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4975 getDeviceOwnerFile());
4976 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4977 }
4978
4979 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4980 throws Exception {
4981 DpmTestUtils.writeInputStreamToFile(
4982 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4983 getDeviceOwnerPoliciesFile());
4984 DpmTestUtils.writeInputStreamToFile(
4985 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4986 getDeviceOwnerFile());
4987 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4988 }
4989
4990 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4991 setupProfileOwner();
4992 initializeDpms();
4993 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4994 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4995 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4996 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4997 }
4998
4999 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5000 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5001 UserHandle.USER_SYSTEM);
5002 DpmTestUtils.writeInputStreamToFile(
5003 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5004 getProfileOwnerPoliciesFile());
5005 DpmTestUtils.writeInputStreamToFile(
5006 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5007 getProfileOwnerFile());
5008 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5009 }
5010
5011 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5012 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5013 UserHandle.USER_SYSTEM);
5014 DpmTestUtils.writeInputStreamToFile(
5015 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5016 getProfileOwnerPoliciesFile());
5017 DpmTestUtils.writeInputStreamToFile(
5018 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5019 getProfileOwnerFile());
5020 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5021 }
5022
5023 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5024 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5025 UserHandle.USER_SYSTEM);
5026 DpmTestUtils.writeInputStreamToFile(
5027 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5028 getProfileOwnerPoliciesFile());
5029 DpmTestUtils.writeInputStreamToFile(
5030 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5031 getProfileOwnerFile());
5032 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5033 }
5034
Eran Messeribb271892018-10-17 18:27:50 +01005035 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5036 setupProfileOwner();
5037 configureContextForAccess(mContext, false);
5038
5039 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005040 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005041 }
5042
5043 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5044 setupProfileOwner();
5045 configureContextForAccess(mContext, false);
5046
5047 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005048 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005049 }
5050
5051 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5052 setupProfileOwner();
5053
5054 // This method will throw if the system context could not call
5055 // setProfileOwnerCanAccessDeviceIds successfully.
5056 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5057 }
5058
5059 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5060 when(context.spiedContext.checkCallingPermission(
5061 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5062 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5063 : PackageManager.PERMISSION_DENIED);
5064 }
5065
5066 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5067 setupProfileOwner();
5068
5069 final long ident = mServiceContext.binder.clearCallingIdentity();
5070 configureContextForAccess(mServiceContext, true);
5071
5072 mServiceContext.binder.callingUid =
5073 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5074 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5075 try {
5076 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005077 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005078 });
5079 } finally {
5080 mServiceContext.binder.restoreCallingIdentity(ident);
5081 }
5082 }
5083
5084 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5085 throws Exception {
5086 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5087 setupDeviceOwner();
5088 configureContextForAccess(mContext, false);
5089
5090 // Device owner should be allowed to request Device ID attestation.
5091 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5092 DpmMockContext.CALLER_SYSTEM_USER_UID);
5093
5094 // Another package must not be allowed to request Device ID attestation.
5095 assertExpectException(SecurityException.class, null,
5096 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5097 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5098 // Another component that is not the admin must not be allowed to request Device ID
5099 // attestation.
5100 assertExpectException(SecurityException.class, null,
5101 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5102 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5103 }
5104
5105 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5106 throws Exception {
5107 configureContextForAccess(mContext, false);
5108
5109 // Make sure a security exception is thrown if the device has no profile owner.
5110 assertExpectException(SecurityException.class, null,
5111 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5112 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5113
5114 setupProfileOwner();
5115 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5116
5117 // The profile owner is allowed to request Device ID attestation.
5118 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5119 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5120 DpmMockContext.CALLER_UID);
5121 // But not another package.
5122 assertExpectException(SecurityException.class, null,
5123 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5124 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5125 // Or another component which is not the admin.
5126 assertExpectException(SecurityException.class, null,
5127 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5128 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5129 }
5130
5131 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5132 final long ident = mServiceContext.binder.clearCallingIdentity();
5133
5134 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5135 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5136 try {
5137 runAsCaller(mServiceContext, dpms, action);
5138 } finally {
5139 mServiceContext.binder.restoreCallingIdentity(ident);
5140 }
5141 }
5142
5143 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5144 setupProfileOwner();
5145 markDelegatedCertInstallerAsInstalled();
5146
5147 // Configure a delegated cert installer.
5148 runAsCaller(mServiceContext, dpms,
5149 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5150 Arrays.asList(DELEGATION_CERT_INSTALL)));
5151
5152 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5153
5154 // Make sure that the profile owner can still request Device ID attestation.
5155 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5156 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5157 DpmMockContext.CALLER_UID);
5158
5159 runAsDelegatedCertInstaller(dpm -> {
5160 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5161 DpmMockContext.DELEGATE_PACKAGE_NAME,
5162 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5163 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5164 });
5165 }
5166
5167 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5168 throws Exception {
5169 setupProfileOwner();
5170 markDelegatedCertInstallerAsInstalled();
5171
5172 // Configure a delegated cert installer.
5173 runAsCaller(mServiceContext, dpms,
5174 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5175 Arrays.asList(DELEGATION_CERT_INSTALL)));
5176
5177
5178 assertExpectException(SecurityException.class, null,
5179 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5180 admin1.getPackageName(),
5181 DpmMockContext.CALLER_UID));
5182
5183 runAsDelegatedCertInstaller(dpm -> {
5184 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5185 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5186 DpmMockContext.DELEGATE_PACKAGE_NAME,
5187 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5188 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5189 });
5190 }
5191
Bernard Chaue9586552018-11-29 10:59:31 +00005192 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5193 assertThrows(SecurityException.class,
5194 () -> new DevicePolicyManagerTestable(
5195 mServiceContext,
5196 dpms,
5197 /* parentInstance= */ true)
5198 .getPasswordComplexity());
5199 }
5200
5201 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5202 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5203 .thenReturn(false);
5204 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5205 }
5206
5207 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5208 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5209 .thenReturn(true);
5210 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5211 }
5212
5213
5214 public void testGetPasswordComplexity_currentUserNoPassword() {
5215 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5216 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005217 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005218 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5219 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5220
5221 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5222 }
5223
5224 public void testGetPasswordComplexity_currentUserHasPassword() {
5225 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5226 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005227 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005228 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5229 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005230 when(getServices().lockSettingsInternal
5231 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5232 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005233
5234 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5235 }
5236
5237 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5238 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5239 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005240 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005241
5242 UserInfo parentUser = new UserInfo();
5243 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5244 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5245 .thenReturn(parentUser.id);
5246
Rubin Xu19854862019-08-15 16:37:23 +01005247 when(getServices().lockSettingsInternal
5248 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5249 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
5250 when(getServices().lockSettingsInternal
5251 .getUserPasswordMetrics(parentUser.id))
5252 .thenReturn(PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005253
5254 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5255 }
5256
yuemingwd2bfbc82019-01-02 11:42:25 +00005257 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5258 setAsProfileOwner(admin1);
5259 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5260 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5261 }
5262
5263 public void testCrossProfileCalendarPackages_reopenDpms() {
5264 setAsProfileOwner(admin1);
5265 dpm.setCrossProfileCalendarPackages(admin1, null);
5266 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5267 assertTrue(packages == null);
5268 initializeDpms();
5269 packages = dpm.getCrossProfileCalendarPackages(admin1);
5270 assertTrue(packages == null);
5271
5272 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5273 packages = dpm.getCrossProfileCalendarPackages(admin1);
5274 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5275 initializeDpms();
5276 packages = dpm.getCrossProfileCalendarPackages(admin1);
5277 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5278
5279 final String dummyPackageName = "test";
5280 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5281 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5282 packages = dpm.getCrossProfileCalendarPackages(admin1);
5283 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5284 initializeDpms();
5285 packages = dpm.getCrossProfileCalendarPackages(admin1);
5286 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5287 }
5288
5289 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5290 assertTrue(expected != null);
5291 assertTrue(actual != null);
5292 assertTrue(expected.containsAll(actual));
5293 assertTrue(actual.containsAll(expected));
5294 }
5295
yuemingwdded98f2019-01-30 17:08:12 +00005296 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5297 setAsProfileOwner(admin1);
5298 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5299 when(getServices().settings.settingsSecureGetIntForUser(
5300 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5301 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5302 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5303 }
5304
5305 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5306 final String testPackage = "TEST_PACKAGE";
5307 setAsProfileOwner(admin1);
5308 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5309 when(getServices().settings.settingsSecureGetIntForUser(
5310 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5311 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5312 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5313 }
5314
5315 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5316 final String testPackage = "TEST_PACKAGE";
5317 setAsProfileOwner(admin1);
5318 dpm.setCrossProfileCalendarPackages(admin1, null);
5319 when(getServices().settings.settingsSecureGetIntForUser(
5320 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5321 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5322 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5323 }
5324
Eran Messeribb271892018-10-17 18:27:50 +01005325 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5326 final long ident = mServiceContext.binder.clearCallingIdentity();
5327 mServiceContext.binder.callingUid =
5328 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5329 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005330 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005331 });
5332 mServiceContext.binder.restoreCallingIdentity(ident);
5333 }
5334
arangelov08d534b2018-01-22 15:20:53 +00005335 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5336 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5337 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5338 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5339
5340 final long ident = mServiceContext.binder.clearCallingIdentity();
5341 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5342 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5343 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5344 // To simulate a reboot, we just reinitialize dpms and call systemReady
5345 initializeDpms();
5346
5347 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5348 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5349 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5350 assertTrue(dpm.isAdminActive(admin1));
5351 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5352 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5353
5354 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5355 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5356 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5357 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5358
5359 mServiceContext.binder.restoreCallingIdentity(ident);
5360 }
5361
5362 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5363 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5364 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5365 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5366
5367 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5368 DpmMockContext.CALLER_SYSTEM_USER_UID);
5369 setUpPackageManagerForAdmin(admin1, uid);
5370 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5371 // To simulate a reboot, we just reinitialize dpms and call systemReady
5372 initializeDpms();
5373
5374 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5375 assertTrue(dpm.isAdminActive(admin1));
5376 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5377 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5378 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5379 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5380 }
5381
5382 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5383 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5384 metadataManager.deleteMetadataFile();
5385
5386 final TransferOwnershipMetadataManager.Metadata metadata =
5387 new TransferOwnershipMetadataManager.Metadata(
5388 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5389 callerUserHandle,
5390 adminType);
5391 metadataManager.saveMetadataFile(metadata);
5392 }
5393
5394 private File getDeviceOwnerFile() {
5395 return dpms.mOwners.getDeviceOwnerFile();
5396 }
5397
5398 private File getProfileOwnerFile() {
5399 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5400 }
5401
5402 private File getProfileOwnerPoliciesFile() {
5403 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5404 DpmMockContext.CALLER_USER_HANDLE);
5405 return getPoliciesFile(parentDir);
5406 }
5407
5408 private File getDeviceOwnerPoliciesFile() {
5409 return getPoliciesFile(getServices().systemUserDataDir);
5410 }
5411
5412 private File getPoliciesFile(File parentDir) {
5413 return new File(parentDir, "device_policies.xml");
5414 }
5415
5416 private InputStream getRawStream(@RawRes int id) {
5417 return mRealTestContext.getResources().openRawResource(id);
5418 }
5419
Victor Chang3e794af2016-03-04 13:48:17 +00005420 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005421 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005422 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5423 dpms.notifyChangeToContentObserver(
5424 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5425 }
5426
5427 private void assertProvisioningAllowed(String action, boolean expected) {
5428 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5429 dpm.isProvisioningAllowed(action));
5430 }
Tony Mak2f26b792016-11-28 17:54:51 +00005431
Nicolas Prevot45d29072017-01-18 16:11:19 +00005432 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5433 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005434 final String previousPackageName = mContext.packageName;
5435 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005436
5437 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5438 mContext.packageName = packageName;
5439 mMockContext.binder.callingUid = uid;
5440 assertProvisioningAllowed(action, expected);
5441
5442 // Set the previous package name / calling uid to go back to the initial state.
5443 mContext.packageName = previousPackageName;
5444 mMockContext.binder.callingUid = previousUid;
5445 }
5446
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005447 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005448 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5449 }
5450
5451 private void assertCheckProvisioningPreCondition(
5452 String action, String packageName, int provisioningCondition) {
5453 assertEquals("checkProvisioningPreCondition("
5454 + action + ", " + packageName + ") returning unexpected result",
5455 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005456 }
5457
Tony Mak2f26b792016-11-28 17:54:51 +00005458 /**
5459 * Setup a managed profile with the specified admin and its uid.
5460 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5461 * @param adminUid uid of the admin package.
5462 * @param copyFromAdmin package information for {@code admin} will be built based on this
5463 * component's information.
5464 */
5465 private void addManagedProfile(
5466 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5467 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005468 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005469 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5470 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5471 dpm.setActiveAdmin(admin, false, userId);
5472 assertTrue(dpm.setProfileOwner(admin, null, userId));
5473 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5474 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005475
5476 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005477 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005478 */
Robin Leeabaa0692017-02-20 20:54:22 +00005479 private static StringParceledListSlice asSlice(String[] s) {
5480 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005481 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005482
5483 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005484 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5485 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005486
Robin Lee2c68dad2017-03-17 12:50:24 +00005487 // We can't let exceptions happen on the background thread. Throw them here if they happen
5488 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005489 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005490 }
Victor Chang3e794af2016-03-04 13:48:17 +00005491}