blob: 162e7669cbc09fe53f5018f1644ede307aa12814 [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 Grafov6f334842019-08-06 14:37:06 +010028import static android.app.admin.PasswordMetrics.computeForPassword;
Pavel Grafov6a40f092016-10-25 15:46:51 +010029
Pavel Grafov6f334842019-08-06 14:37:06 +010030import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080031import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070032import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010033
Pavel Grafov75c0a892017-05-18 17:28:27 +010034import static org.mockito.Matchers.any;
35import static org.mockito.Matchers.anyInt;
36import static org.mockito.Matchers.anyLong;
37import static org.mockito.Matchers.anyObject;
38import static org.mockito.Matchers.anyString;
39import static org.mockito.Matchers.eq;
40import static org.mockito.Matchers.isNull;
41import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010042import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010043import static org.mockito.Mockito.doAnswer;
44import static org.mockito.Mockito.doReturn;
45import static org.mockito.Mockito.never;
46import static org.mockito.Mockito.nullable;
47import static org.mockito.Mockito.reset;
48import static org.mockito.Mockito.timeout;
49import static org.mockito.Mockito.times;
50import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080051import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010052import static org.mockito.Mockito.verifyZeroInteractions;
53import static org.mockito.Mockito.when;
54import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000055import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056
Makoto Onukif76b06a2015-09-22 15:03:44 -070057import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000058import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010060import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000061import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062import android.app.admin.DeviceAdminReceiver;
63import android.app.admin.DevicePolicyManager;
64import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010065import android.app.admin.PasswordMetrics;
Neil Fullere3767562019-11-23 11:33:57 +000066import android.app.timedetector.ManualTimeSuggestion;
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;
Alex Johnstonece5cdb2019-11-20 14:37:13 +000083import android.os.UserManagerInternal;
Pavel Grafovc14b3172017-07-03 13:15:11 +010084import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080085import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010086import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000087import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000088import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000089import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080090import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010091import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070092import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093
Pavel Grafov57f1b662019-03-27 14:55:38 +000094import androidx.test.filters.SmallTest;
95
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010096import com.android.internal.R;
Rubin Xua58125d2019-09-06 20:11:48 +010097import com.android.internal.widget.LockscreenCredential;
Alan Treadwayafad8782016-01-19 15:15:08 +000098import com.android.server.LocalServices;
99import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +0000100import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000101import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000102
Robin Lee7f5c91c2017-02-08 21:27:02 +0000103import org.hamcrest.BaseMatcher;
104import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800105import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700106import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107
arangelov08d534b2018-01-22 15:20:53 +0000108import java.io.File;
109import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800110import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000111import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000112import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700113import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700114import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700115import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100116import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000117import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700120 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000121 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122 m FrameworksServicesTests &&
123 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000124 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700126 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700127
128 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000129 *
130 * , or:
131 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700132 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000133@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100134@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700135public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000136 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
137 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
138 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100139 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800140 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100141 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000142
Pavel Grafov75c0a892017-05-18 17:28:27 +0100143 // TODO replace all instances of this with explicit {@link #mServiceContext}.
144 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700145 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100146
147 private DpmMockContext mServiceContext;
148 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700149 public DevicePolicyManager dpm;
150 public DevicePolicyManagerServiceTestable dpms;
151
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100152 /*
153 * The CA cert below is the content of cacert.pem as generated by:
154 *
155 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
156 */
157 private static final String TEST_CA =
158 "-----BEGIN CERTIFICATE-----\n" +
159 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
160 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
161 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
162 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
163 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
164 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
165 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
166 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
167 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
168 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
169 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
170 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
171 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
172 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
173 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
174 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
175 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
176 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
177 "wQ==\n" +
178 "-----END CERTIFICATE-----\n";
179
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700180 @Override
181 protected void setUp() throws Exception {
182 super.setUp();
183
184 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100185 mServiceContext = mContext;
186 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
187 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700188 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100189 doReturn(Collections.singletonList(new ResolveInfo()))
190 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
191 any(Intent.class),
192 anyInt(),
193 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700194
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800195 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100196 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800197
Makoto Onukia52562c2015-10-01 16:12:31 -0700198 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700199
Sudheer Shanka101c3532018-01-08 16:28:42 -0800200 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800201 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700202 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
203 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
204 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800205 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700206
Pavel Grafov75c0a892017-05-18 17:28:27 +0100207 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
208 mAdmin1Context.packageName = admin1.getPackageName();
209 mAdmin1Context.applicationInfo = new ApplicationInfo();
210 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
211
Makoto Onukib643fb02015-09-22 15:03:44 -0700212 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100213
214 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700215 }
216
arangelov08d534b2018-01-22 15:20:53 +0000217 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
218 return dpms.mTransferOwnershipMetadataManager;
219 }
220
Robin Lee2c68dad2017-03-17 12:50:24 +0000221 @Override
222 protected void tearDown() throws Exception {
223 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000224 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000225 super.tearDown();
226 }
227
Makoto Onukia52562c2015-10-01 16:12:31 -0700228 private void initializeDpms() {
229 // Need clearCallingIdentity() to pass permission checks.
230 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100231 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700232
Pavel Grafov75c0a892017-05-18 17:28:27 +0100233 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
234 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
235 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236
Pavel Grafov75c0a892017-05-18 17:28:27 +0100237 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700238
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700240 }
241
Makoto Onukib643fb02015-09-22 15:03:44 -0700242 private void setUpUserManager() {
243 // Emulate UserManager.set/getApplicationRestriction().
244 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
245
246 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000247 doAnswer((Answer<Void>) invocation -> {
248 String pkg = (String) invocation.getArguments()[0];
249 Bundle bundle = (Bundle) invocation.getArguments()[1];
250 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700251
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000252 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700253
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000254 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100255 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100256 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700257
258 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000259 doAnswer((Answer<Bundle>) invocation -> {
260 String pkg = (String) invocation.getArguments()[0];
261 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700262
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000263 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100264 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700265 anyString(), any(UserHandle.class));
266
Makoto Onukid932f762015-09-29 16:53:38 -0700267 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100268 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700269 }
270
271 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700273
Pavel Grafov75c0a892017-05-18 17:28:27 +0100274 mServiceContext.binder.callingUid =
275 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
276 runAsCaller(mServiceContext, dpms, dpm -> {
277 // PO needs to be a DA.
278 dpm.setActiveAdmin(admin, /*replace=*/ false);
279 // Fire!
280 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
281 // Check
282 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
283 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700284
Pavel Grafov75c0a892017-05-18 17:28:27 +0100285 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700286 }
287
288 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100289 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700290 .thenReturn(false);
291
292 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100293 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700294
295 // If the device has no DPMS feature, it shouldn't register the local service.
296 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
297 }
298
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800299 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800300 // Device owner in SYSTEM_USER
301 setDeviceOwner();
302 // Profile owner in CALLER_USER_HANDLE
303 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
304 setAsProfileOwner(admin2);
305 // Active admin in CALLER_USER_HANDLE
306 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
307 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
308 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
309 DpmMockContext.CALLER_USER_HANDLE);
310 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
311 DpmMockContext.CALLER_USER_HANDLE));
312
313 initializeDpms();
314
315 // Verify
316 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800317 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800318 eq(UserHandle.USER_SYSTEM));
319 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800320 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800321 adminAnotherPackage.getPackageName()),
322 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800323 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
324 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
325 }
326
327 public void testLoadAdminData_noAdmins() throws Exception {
328 final int ANOTHER_USER_ID = 15;
329 getServices().addUser(ANOTHER_USER_ID, 0);
330
331 initializeDpms();
332
333 // Verify
334 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
335 null, DpmMockContext.CALLER_USER_HANDLE);
336 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
337 null, ANOTHER_USER_ID);
338 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
339 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800340 }
341
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700342 /**
343 * Caller doesn't have proper permissions.
344 */
345 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700346 // 1. Failure cases.
347
348 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100349 assertExpectException(SecurityException.class, /* messageRegex= */ null,
350 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700351
352 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
353 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100354
355 assertExpectException(SecurityException.class, /* messageRegex= */ null,
356 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700357 }
358
Makoto Onukif76b06a2015-09-22 15:03:44 -0700359 /**
360 * Test for:
361 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800362 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700363 * {@link DevicePolicyManager#isAdminActive}
364 * {@link DevicePolicyManager#isAdminActiveAsUser}
365 * {@link DevicePolicyManager#getActiveAdmins}
366 * {@link DevicePolicyManager#getActiveAdminsAsUser}
367 */
368 public void testSetActiveAdmin() throws Exception {
369 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700370 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
371
Makoto Onukif76b06a2015-09-22 15:03:44 -0700372 // 2. Call the API.
373 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700374
375 // 3. Verify internal calls.
376
377 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700378 verify(mContext.spiedContext).sendBroadcastAsUser(
379 MockUtils.checkIntentAction(
380 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
381 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
382 verify(mContext.spiedContext).sendBroadcastAsUser(
383 MockUtils.checkIntentAction(
384 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100385 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
386 eq(null),
387 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700388
Pavel Grafov75c0a892017-05-18 17:28:27 +0100389 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700390 eq(admin1.getPackageName()),
391 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
392 eq(PackageManager.DONT_KILL_APP),
393 eq(DpmMockContext.CALLER_USER_HANDLE),
394 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700395
Sudheer Shanka101c3532018-01-08 16:28:42 -0800396 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
397 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
398
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700399 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700400
401 // Make sure it's active admin1.
402 assertTrue(dpm.isAdminActive(admin1));
403 assertFalse(dpm.isAdminActive(admin2));
404 assertFalse(dpm.isAdminActive(admin3));
405
406 // But not admin1 for a different user.
407
408 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
409 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
410 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
411
412 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
413 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
414
415 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
416
417 // Next, add one more admin.
418 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700419 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700420 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700421
422 dpm.setActiveAdmin(admin2, /* replace =*/ false);
423
424 // Now we have two admins.
425 assertTrue(dpm.isAdminActive(admin1));
426 assertTrue(dpm.isAdminActive(admin2));
427 assertFalse(dpm.isAdminActive(admin3));
428
429 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
430 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100431 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700432 eq(admin1.getPackageName()),
433 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
434 eq(PackageManager.DONT_KILL_APP),
435 eq(DpmMockContext.CALLER_USER_HANDLE),
436 anyString());
437
Sudheer Shanka101c3532018-01-08 16:28:42 -0800438 // times(2) because it was previously called for admin1 which is in the same package
439 // as admin2.
440 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
441 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
442
Makoto Onukif76b06a2015-09-22 15:03:44 -0700443 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100444 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
445 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700446
447 // 5. Add the same admin1 again with replace, which should succeed.
448 dpm.setActiveAdmin(admin1, /* replace =*/ true);
449
450 // TODO make sure it's replaced.
451
452 // 6. Test getActiveAdmins()
453 List<ComponentName> admins = dpm.getActiveAdmins();
454 assertEquals(2, admins.size());
455 assertEquals(admin1, admins.get(0));
456 assertEquals(admin2, admins.get(1));
457
Sudheer Shanka101c3532018-01-08 16:28:42 -0800458 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
459 // replaced
460 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
461
Makoto Onukif76b06a2015-09-22 15:03:44 -0700462 // Another user has no admins.
463 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
464
465 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
466 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
467
468 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
469 }
470
Makoto Onukid932f762015-09-29 16:53:38 -0700471 public void testSetActiveAdmin_multiUsers() throws Exception {
472
473 final int ANOTHER_USER_ID = 100;
474 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
475
Pavel Grafov75c0a892017-05-18 17:28:27 +0100476 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700477
478 // Set up pacakge manager for the other user.
479 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700480
481 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
482
483 dpm.setActiveAdmin(admin1, /* replace =*/ false);
484
485 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
486 dpm.setActiveAdmin(admin2, /* replace =*/ false);
487
488
489 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
490 assertTrue(dpm.isAdminActive(admin1));
491 assertFalse(dpm.isAdminActive(admin2));
492
493 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
494 assertFalse(dpm.isAdminActive(admin1));
495 assertTrue(dpm.isAdminActive(admin2));
496 }
497
Makoto Onukif76b06a2015-09-22 15:03:44 -0700498 /**
499 * Test for:
500 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800501 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700502 */
503 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
504 // 1. Make sure the caller has proper permissions.
505 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
506
507 dpm.setActiveAdmin(admin1, /* replace =*/ false);
508 assertTrue(dpm.isAdminActive(admin1));
509
510 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100511 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
512 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700513 }
514
515 /**
516 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800517 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
518 * BIND_DEVICE_ADMIN.
519 */
520 public void testSetActiveAdmin_permissionCheck() throws Exception {
521 // 1. Make sure the caller has proper permissions.
522 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
523
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100524 assertExpectException(IllegalArgumentException.class,
525 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
526 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800527 assertFalse(dpm.isAdminActive(adminNoPerm));
528
529 // Change the target API level to MNC. Now it can be set as DA.
530 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
531 VERSION_CODES.M);
532 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
533 assertTrue(dpm.isAdminActive(adminNoPerm));
534
535 // TODO Test the "load from the file" case where DA will still be loaded even without
536 // BIND_DEVICE_ADMIN and target API is N.
537 }
538
539 /**
540 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700541 * {@link DevicePolicyManager#removeActiveAdmin}
542 */
543 public void testRemoveActiveAdmin_SecurityException() {
544 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
545
546 // Add admin.
547
548 dpm.setActiveAdmin(admin1, /* replace =*/ false);
549
550 assertTrue(dpm.isAdminActive(admin1));
551
552 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
553
554 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100555 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
556 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700557
558 // Try to remove active admin with a different caller userid should fail too, without
559 // having MANAGE_DEVICE_ADMINS.
560 mContext.callerPermissions.clear();
561
Makoto Onukid932f762015-09-29 16:53:38 -0700562 // Change the caller, and call into DPMS directly with a different user-id.
563
Makoto Onukif76b06a2015-09-22 15:03:44 -0700564 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100565 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
566 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700567 }
568
569 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800570 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
571 * (because we can't send the remove broadcast).
572 */
573 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
574 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
575
576 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
577
578 // Add admin.
579
580 dpm.setActiveAdmin(admin1, /* replace =*/ false);
581
582 assertTrue(dpm.isAdminActive(admin1));
583
584 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
585
586 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100587 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800588 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100589 assertExpectException(IllegalStateException.class,
590 /* messageRegex= */ "User must be running and unlocked",
591 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800592
593 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800594 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
595 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800596
597 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100598 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800599 .thenReturn(true);
600
601 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700602 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800603 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
604 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800605 }
606
607 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700608 * Test for:
609 * {@link DevicePolicyManager#removeActiveAdmin}
610 */
Makoto Onukid932f762015-09-29 16:53:38 -0700611 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700612 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
613
614 // Add admin1.
615
616 dpm.setActiveAdmin(admin1, /* replace =*/ false);
617
618 assertTrue(dpm.isAdminActive(admin1));
619 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
620
621 // Different user, but should work, because caller has proper permissions.
622 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700623
624 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700625 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700626
627 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700628 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800629 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
630 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700631
632 // TODO DO Still can't be removed in this case.
633 }
634
635 /**
636 * Test for:
637 * {@link DevicePolicyManager#removeActiveAdmin}
638 */
639 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
640 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
641 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
642
643 // Add admin1.
644
645 dpm.setActiveAdmin(admin1, /* replace =*/ false);
646
647 assertTrue(dpm.isAdminActive(admin1));
648 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
649
650 // Broadcast from saveSettingsLocked().
651 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
652 MockUtils.checkIntentAction(
653 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
654 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
655
656 // Remove. No permissions, but same user, so it'll work.
657 mContext.callerPermissions.clear();
658 dpm.removeActiveAdmin(admin1);
659
Makoto Onukif76b06a2015-09-22 15:03:44 -0700660 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
661 MockUtils.checkIntentAction(
662 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
663 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
664 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100665 eq(AppOpsManager.OP_NONE),
666 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700667 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700668 eq(dpms.mHandler),
669 eq(Activity.RESULT_OK),
670 isNull(String.class),
671 isNull(Bundle.class));
672
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700673 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800674 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
675 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700676
677 // Again broadcast from saveSettingsLocked().
678 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
679 MockUtils.checkIntentAction(
680 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
681 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
682
683 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700684 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700685
Sudheer Shanka101c3532018-01-08 16:28:42 -0800686 public void testRemoveActiveAdmin_multipleAdminsInUser() {
687 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
688 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
689
690 // Add admin1.
691 dpm.setActiveAdmin(admin1, /* replace =*/ false);
692
693 assertTrue(dpm.isAdminActive(admin1));
694 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
695
696 // Add admin2.
697 dpm.setActiveAdmin(admin2, /* replace =*/ false);
698
699 assertTrue(dpm.isAdminActive(admin2));
700 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
701
702 // Broadcast from saveSettingsLocked().
703 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
704 MockUtils.checkIntentAction(
705 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
706 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
707
708 // Remove. No permissions, but same user, so it'll work.
709 mContext.callerPermissions.clear();
710 dpm.removeActiveAdmin(admin1);
711
712 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
713 MockUtils.checkIntentAction(
714 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
715 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
716 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100717 eq(AppOpsManager.OP_NONE),
718 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800719 any(BroadcastReceiver.class),
720 eq(dpms.mHandler),
721 eq(Activity.RESULT_OK),
722 isNull(String.class),
723 isNull(Bundle.class));
724
725 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
726 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800727 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800728 eq(DpmMockContext.CALLER_USER_HANDLE));
729
730 // Again broadcast from saveSettingsLocked().
731 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
732 MockUtils.checkIntentAction(
733 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
734 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
735 }
736
737 /**
738 * Test for:
739 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
740 */
741 public void testForceRemoveActiveAdmin() throws Exception {
742 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
743
744 // Add admin.
745 setupPackageInPackageManager(admin1.getPackageName(),
746 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
747 /* appId= */ 10138,
748 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
749 dpm.setActiveAdmin(admin1, /* replace =*/ false);
750 assertTrue(dpm.isAdminActive(admin1));
751
752 // Calling from a non-shell uid should fail with a SecurityException
753 mContext.binder.callingUid = 123456;
754 assertExpectException(SecurityException.class,
755 /* messageRegex =*/ "Non-shell user attempted to call",
756 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
757
758 mContext.binder.callingUid = Process.SHELL_UID;
759 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
760
761 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
762 // Verify
763 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
764 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
765 null, DpmMockContext.CALLER_USER_HANDLE);
766 }
767
Makoto Onukib643fb02015-09-22 15:03:44 -0700768 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100769 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
770 *
771 * Validates that when the password history length is set, it is persisted after rebooting
772 */
773 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
774 int passwordHistoryLength = 2;
775
776 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
777 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
778 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
779
780 // Install admin1 on system user.
781 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
782
783 // Set admin1 to active admin and device owner
784 dpm.setActiveAdmin(admin1, false);
785 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
786
787 // Save password history length
788 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
789
790 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
791
792 initializeDpms();
793 reset(mContext.spiedContext);
794
795 // Password history length should persist after rebooted
796 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
797 }
798
799 /**
800 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000801 *
802 * Validates that when the password for a user changes, the notification broadcast intent
803 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
804 * addition to ones in the original user.
805 */
806 public void testSetActivePasswordState_sendToProfiles() throws Exception {
807 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
808
809 final int MANAGED_PROFILE_USER_ID = 78;
810 final int MANAGED_PROFILE_ADMIN_UID =
811 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
812
813 // Setup device owner.
814 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
815 mContext.packageName = admin1.getPackageName();
816 setupDeviceOwner();
817
818 // Add a managed profile belonging to the system user.
819 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
820
821 // Change the parent user's password.
822 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
823
824 // Both the device owner and the managed profile owner should receive this broadcast.
825 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
826 intent.setComponent(admin1);
827 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
828
829 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
830 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100831 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
832 eq(null),
833 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000834 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
835 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100836 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
837 eq(null),
838 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000839 }
840
841 /**
Rubin Xu19854862019-08-15 16:37:23 +0100842 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000843 *
844 * Validates that when the password for a managed profile changes, the notification broadcast
845 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
846 * its parent.
847 */
848 public void testSetActivePasswordState_notSentToParent() throws Exception {
849 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
850
851 final int MANAGED_PROFILE_USER_ID = 78;
852 final int MANAGED_PROFILE_ADMIN_UID =
853 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
854
855 // Setup device owner.
856 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
857 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100858 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000859 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
860 setupDeviceOwner();
861
862 // Add a managed profile belonging to the system user.
863 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
864
865 // Change the profile's password.
866 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
867
868 // Both the device owner and the managed profile owner should receive this broadcast.
869 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
870 intent.setComponent(admin1);
871 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
872
873 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
874 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100875 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
876 eq(null),
877 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000878 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
879 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100880 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
881 eq(null),
882 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000883 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100884
Robin Leed2a73ed2016-12-19 09:07:16 +0000885 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000886 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700887 */
888 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000889 setDeviceOwner();
890
891 // Try to set a profile owner on the same user, which should fail.
892 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
893 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100894 assertExpectException(IllegalStateException.class,
895 /* messageRegex= */ "already has a device owner",
896 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000897
898 // DO admin can't be deactivated.
899 dpm.removeActiveAdmin(admin1);
900 assertTrue(dpm.isAdminActive(admin1));
901
902 // TODO Test getDeviceOwnerName() too. To do so, we need to change
903 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
904 }
905
906 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700907 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800908 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700909 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
910 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
911
Makoto Onukid932f762015-09-29 16:53:38 -0700912 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
914
Makoto Onukid932f762015-09-29 16:53:38 -0700915 // Make sure admin1 is installed on system user.
916 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700917
Makoto Onukic8a5a552015-11-19 14:29:12 -0800918 // Check various get APIs.
919 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
920
Makoto Onukib643fb02015-09-22 15:03:44 -0700921 // DO needs to be an DA.
922 dpm.setActiveAdmin(admin1, /* replace =*/ false);
923
924 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700925 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700926
Makoto Onukic8a5a552015-11-19 14:29:12 -0800927 // getDeviceOwnerComponent should return the admin1 component.
928 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
929 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
930
931 // Check various get APIs.
932 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
933
934 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
935 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
936 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
937 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
938
939 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
940
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000941 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100942 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000943 eq(admin1.getPackageName()));
944
Makoto Onukib643fb02015-09-22 15:03:44 -0700945 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
946 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
947 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
948
Makoto Onukic8a5a552015-11-19 14:29:12 -0800949 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700950 }
951
Makoto Onukic8a5a552015-11-19 14:29:12 -0800952 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
953 final int origCallingUser = mContext.binder.callingUid;
954 final List origPermissions = new ArrayList(mContext.callerPermissions);
955 mContext.callerPermissions.clear();
956
957 mContext.callerPermissions.add(permission.MANAGE_USERS);
958
959 mContext.binder.callingUid = Process.SYSTEM_UID;
960
961 // TODO Test getDeviceOwnerName() too. To do so, we need to change
962 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
963 if (hasDeviceOwner) {
964 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
965 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
966 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
967
968 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
970 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
971 } else {
972 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
973 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
974 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
975
976 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
977 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
978 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
979 }
980
981 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
982 if (hasDeviceOwner) {
983 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
984 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
985 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
986
987 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
989 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
990 } else {
991 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
992 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
993 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
994
995 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
996 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
997 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
998 }
999
1000 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1001 // Still with MANAGE_USERS.
1002 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1003 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1004 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1005
1006 if (hasDeviceOwner) {
1007 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1008 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1009 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1010 } else {
1011 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1012 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1013 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1014 }
1015
1016 mContext.binder.callingUid = Process.SYSTEM_UID;
1017 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1018 // System can still call "OnAnyUser" without MANAGE_USERS.
1019 if (hasDeviceOwner) {
1020 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1021 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1022 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1023
1024 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1025 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1026 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1027 } else {
1028 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1029 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1030 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1031
1032 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1033 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1034 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1035 }
1036
1037 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1038 // Still no MANAGE_USERS.
1039 if (hasDeviceOwner) {
1040 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1041 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1042 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1043 } else {
1044 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1045 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1046 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1047 }
1048
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001049 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1050 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1051 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1052 dpm::getDeviceOwnerComponentOnAnyUser);
1053 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1054 dpm::getDeviceOwnerUserId);
1055 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1056 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001057
1058 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1059 // Still no MANAGE_USERS.
1060 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1061 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1062 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1063
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001064 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1065 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1066 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1067 dpm::getDeviceOwnerComponentOnAnyUser);
1068 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1069 dpm::getDeviceOwnerUserId);
1070 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1071 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001072
1073 // Restore.
1074 mContext.binder.callingUid = origCallingUser;
1075 mContext.callerPermissions.addAll(origPermissions);
1076 }
1077
1078
Makoto Onukib643fb02015-09-22 15:03:44 -07001079 /**
1080 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1081 */
1082 public void testSetDeviceOwner_noSuchPackage() {
1083 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001084 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001085 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1086 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1087
1088 // Call from a process on the system user.
1089 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1090
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001091 assertExpectException(IllegalArgumentException.class,
1092 /* messageRegex= */ "Invalid component",
1093 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001094 }
1095
1096 public void testSetDeviceOwner_failures() throws Exception {
1097 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1098 }
1099
Makoto Onukia52562c2015-10-01 16:12:31 -07001100 public void testClearDeviceOwner() throws Exception {
1101 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001102 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1104 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1105
1106 // Set admin1 as a DA to the secondary user.
1107 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1108
1109 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1110
1111 // Set admin 1 as the DO to the system user.
1112
1113 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1114 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1115 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1116 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1117
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001118 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001119 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001120 eq(admin1.getPackageName()));
1121
Makoto Onukic8a5a552015-11-19 14:29:12 -08001122 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001123
Makoto Onuki90b89652016-01-28 14:44:18 -08001124 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001125 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001126 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001127
1128 assertTrue(dpm.isAdminActive(admin1));
1129 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1130
Makoto Onukia52562c2015-10-01 16:12:31 -07001131 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001132 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001133
1134 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001135 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1136 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001137
1138 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001139 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001140 assertExpectException(IllegalStateException.class,
1141 /* messageRegex= */ "User must be running and unlocked",
1142 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001143
Pavel Grafov75c0a892017-05-18 17:28:27 +01001144 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1145 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001146 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1147
1148 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001149 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001150
Pavel Grafov75c0a892017-05-18 17:28:27 +01001151 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001152 eq(false),
1153 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1154
Pavel Grafov75c0a892017-05-18 17:28:27 +01001155 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001156 eq(UserHandle.USER_SYSTEM), eq(null),
1157 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Makoto Onuki90b89652016-01-28 14:44:18 -08001158
Sudheer Shanka101c3532018-01-08 16:28:42 -08001159 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1160 null, UserHandle.USER_SYSTEM);
1161
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001162 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001163
1164 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1165 // and once for clearing it.
1166 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1167 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1168 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001169 // TODO Check other calls.
1170 }
1171
Pavel Grafov775b26d82019-10-30 13:29:01 +00001172 public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1173 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1174 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1175
1176 // Set admin1 as a DA to the secondary user.
1177 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1178 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1179 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1180 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1181
1182 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1183 eq(UserHandle.USER_SYSTEM), eq(false));
1184
1185 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1186
1187 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1188 eq(UserHandle.USER_SYSTEM), eq(true));
1189 }
1190
1191 public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1192 setAsProfileOwner(admin1);
1193
1194 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1195 eq(DpmMockContext.CALLER_USER_HANDLE), eq(false));
1196
1197 dpm.clearProfileOwner(admin1);
1198
1199 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1200 eq(DpmMockContext.CALLER_USER_HANDLE), eq(true));
1201 }
1202
Makoto Onukia52562c2015-10-01 16:12:31 -07001203 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1204 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001205 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001206 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1207 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1208
1209 // Set admin1 as a DA to the secondary user.
1210 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1211
1212 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1213
1214 // Set admin 1 as the DO to the system user.
1215
1216 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1217 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1218 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1219 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1220
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001221 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001222 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001223 eq(admin1.getPackageName()));
1224
Makoto Onukic8a5a552015-11-19 14:29:12 -08001225 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001226
1227 // Now call clear from the secondary user, which should throw.
1228 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1229
1230 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001231 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 eq(admin1.getPackageName()),
1233 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001234 assertExpectException(SecurityException.class,
1235 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1236 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001237
Makoto Onukic8a5a552015-11-19 14:29:12 -08001238 // DO shouldn't be removed.
1239 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001240 }
1241
Alex Johnston63220932019-09-26 10:10:51 +01001242 /**
1243 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1244 *
1245 * Validates that when the device owner is removed, the reset password token is cleared
1246 */
1247 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1248 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1250 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1251
1252 // Install admin1 on system user
1253 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1254
1255 // Set admin1 to active admin and device owner
1256 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1257 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1258
1259 // Add reset password token
1260 final long handle = 12000;
1261 final byte[] token = new byte[32];
1262 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1263 nullable(EscrowTokenStateChangeCallback.class)))
1264 .thenReturn(handle);
1265 assertTrue(dpm.setResetPasswordToken(admin1, token));
1266
1267 // Assert reset password token is active
1268 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1269 eq(UserHandle.USER_SYSTEM)))
1270 .thenReturn(true);
1271 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1272
1273 // Remove the device owner
1274 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1275
1276 // Verify password reset password token was removed
1277 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1278 eq(UserHandle.USER_SYSTEM));
1279 }
1280
Makoto Onukib643fb02015-09-22 15:03:44 -07001281 public void testSetProfileOwner() throws Exception {
1282 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001283
Makoto Onuki90b89652016-01-28 14:44:18 -08001284 // PO admin can't be deactivated.
1285 dpm.removeActiveAdmin(admin1);
1286 assertTrue(dpm.isAdminActive(admin1));
1287
Makoto Onuki803d6752015-10-30 12:58:39 -07001288 // Try setting DO on the same user, which should fail.
1289 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001290 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1291 runAsCaller(mServiceContext, dpms, dpm -> {
1292 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001293 assertExpectException(IllegalStateException.class,
1294 /* messageRegex= */ "already has a profile owner",
1295 () -> dpm.setDeviceOwner(admin2, "owner-name",
1296 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001297 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001298 }
1299
Makoto Onuki90b89652016-01-28 14:44:18 -08001300 public void testClearProfileOwner() throws Exception {
1301 setAsProfileOwner(admin1);
1302
1303 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1304
1305 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1306 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1307
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001308 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001309 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001310 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001311 assertExpectException(IllegalStateException.class,
1312 /* messageRegex= */ "User must be running and unlocked",
1313 () -> dpm.clearProfileOwner(admin1));
1314
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001315 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001316 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001317 dpm.clearProfileOwner(admin1);
1318
1319 // Check
1320 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001321 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001322 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1323 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001324 }
1325
Makoto Onukib643fb02015-09-22 15:03:44 -07001326 public void testSetProfileOwner_failures() throws Exception {
1327 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1328 }
1329
Makoto Onukia52562c2015-10-01 16:12:31 -07001330 public void testGetDeviceOwnerAdminLocked() throws Exception {
1331 checkDeviceOwnerWithMultipleDeviceAdmins();
1332 }
1333
1334 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1335 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1336 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1337 // make sure it gets the right component from the right user.
1338
1339 final int ANOTHER_USER_ID = 100;
1340 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1341
Pavel Grafov75c0a892017-05-18 17:28:27 +01001342 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001343
1344 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001345 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001346 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1347 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1348
1349 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1350
Pavel Grafov75c0a892017-05-18 17:28:27 +01001351 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001352
Makoto Onukia52562c2015-10-01 16:12:31 -07001353 // Make sure the admin packge is installed to each user.
1354 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1355 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1356
1357 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1358 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1359
1360 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1361
1362
1363 // Set active admins to the users.
1364 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1365 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1366
1367 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1368 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1369
1370 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1371
1372 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001373 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001374 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1375
Makoto Onukic8a5a552015-11-19 14:29:12 -08001376 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001377
1378 // Then check getDeviceOwnerAdminLocked().
1379 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1380 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1381 }
1382
1383 /**
1384 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001385 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1386 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001387 *
1388 * We didn't use to persist the DO component class name, but now we do, and the above method
1389 * finds the right component from a package name upon migration.
1390 */
1391 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001392 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001393 checkDeviceOwnerWithMultipleDeviceAdmins();
1394
1395 // Overwrite the device owner setting and clears the clas name.
1396 dpms.mOwners.setDeviceOwner(
1397 new ComponentName(admin2.getPackageName(), ""),
1398 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1399 dpms.mOwners.writeDeviceOwner();
1400
1401 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001402 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001403
1404 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001405 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001406 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001407 initializeDpms();
1408
1409 // Now the DO component name is a full name.
1410 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1411 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001412 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001413 }
1414
Makoto Onukib643fb02015-09-22 15:03:44 -07001415 public void testSetGetApplicationRestriction() {
1416 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001417 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001418
1419 {
1420 Bundle rest = new Bundle();
1421 rest.putString("KEY_STRING", "Foo1");
1422 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1423 }
1424
1425 {
1426 Bundle rest = new Bundle();
1427 rest.putString("KEY_STRING", "Foo2");
1428 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1429 }
1430
1431 {
1432 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1433 assertNotNull(returned);
1434 assertEquals(returned.size(), 1);
1435 assertEquals(returned.get("KEY_STRING"), "Foo1");
1436 }
1437
1438 {
1439 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1440 assertNotNull(returned);
1441 assertEquals(returned.size(), 1);
1442 assertEquals(returned.get("KEY_STRING"), "Foo2");
1443 }
1444
1445 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1446 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1447 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001448
Edman Anjosf9946772016-11-28 16:35:15 +01001449 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001450 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1451 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001452 *
1453 * @param packageName the name of the package to be setup
1454 * @param appId the application ID to be given to the package
1455 * @return the UID of the package as known by the mock package manager
1456 */
1457 private int setupPackageInPackageManager(final String packageName, final int appId)
1458 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001459 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001460 ApplicationInfo.FLAG_HAS_CODE);
1461 }
1462
1463 /**
1464 * Setup a package in the package manager mock. Useful for faking installed applications.
1465 *
1466 * @param packageName the name of the package to be setup
1467 * @param userId the user id where the package will be "installed"
1468 * @param appId the application ID to be given to the package
1469 * @param flags flags to set in the ApplicationInfo for this package
1470 * @return the UID of the package as known by the mock package manager
1471 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001472 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1473 int flags) throws Exception {
1474 final int uid = UserHandle.getUid(userId, appId);
1475 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001476 final PackageInfo pi = new PackageInfo();
1477 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001478 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001479 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001480 eq(packageName),
1481 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001482 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001483 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001484 eq(packageName),
1485 anyInt(),
1486 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001487 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001488 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001489 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001490 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001491 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001492 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001493 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001494 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001495 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001496 return uid;
1497 }
1498
Robin Lee7f5c91c2017-02-08 21:27:02 +00001499 public void testCertificateDisclosure() throws Exception {
1500 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1501 final UserHandle user = UserHandle.of(userId);
1502
1503 mContext.applicationInfo = new ApplicationInfo();
1504 mContext.callerPermissions.add(permission.MANAGE_USERS);
1505 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001506 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001507 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1508
Robin Leeabaa0692017-02-20 20:54:22 +00001509 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1510 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001511
1512 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1513 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1514
1515 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001516 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001517 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001518 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001519 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001520 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001521 .cancelAsUser(anyString(), anyInt(), eq(user));
1522
1523 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001524 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001525 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001526 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1527 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001528 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001529 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001530 .notifyAsUser(anyString(), anyInt(), argThat(
1531 new BaseMatcher<Notification>() {
1532 @Override
1533 public boolean matches(Object item) {
1534 final Notification noti = (Notification) item;
1535 return TEST_STRING.equals(
1536 noti.extras.getString(Notification.EXTRA_TITLE));
1537 }
1538 @Override
1539 public void describeTo(Description description) {
1540 description.appendText(
1541 "Notification{title=\"" + TEST_STRING + "\"}");
1542 }
1543 }), eq(user));
1544 }
1545
Edman Anjosf9946772016-11-28 16:35:15 +01001546 /**
1547 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1548 * privileges can acually be exercised by a delegate are not covered here.
1549 */
1550 public void testDelegation() throws Exception {
1551 setAsProfileOwner(admin1);
1552
1553 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1554
1555 // Given two packages
1556 final String CERT_DELEGATE = "com.delegate.certs";
1557 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1558 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1559 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1560 20989);
1561
1562 // On delegation
1563 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1564 mContext.packageName = admin1.getPackageName();
1565 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1566 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1567
1568 // DPMS correctly stores and retrieves the delegates
1569 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1570 assertEquals(2, policy.mDelegationMap.size());
1571 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1572 DELEGATION_CERT_INSTALL);
1573 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1574 DELEGATION_CERT_INSTALL);
1575 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1576 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1577 DELEGATION_APP_RESTRICTIONS);
1578 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1579 DELEGATION_APP_RESTRICTIONS);
1580 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1581
1582 // On calling install certificate APIs from an unauthorized process
1583 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1584 mContext.packageName = RESTRICTIONS_DELEGATE;
1585
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001586 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1587 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001588
1589 // On calling install certificate APIs from an authorized process
1590 mContext.binder.callingUid = CERT_DELEGATE_UID;
1591 mContext.packageName = CERT_DELEGATE;
1592
1593 // DPMS executes without a SecurityException
1594 try {
1595 dpm.installCaCert(null, null);
1596 } catch (SecurityException unexpected) {
1597 fail("Threw SecurityException on authorized access");
1598 } catch (NullPointerException expected) {
1599 }
1600
1601 // On removing a delegate
1602 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1603 mContext.packageName = admin1.getPackageName();
1604 dpm.setCertInstallerPackage(admin1, null);
1605
1606 // DPMS does not allow access to ex-delegate
1607 mContext.binder.callingUid = CERT_DELEGATE_UID;
1608 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001609 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1610 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001611
1612 // But still allows access to other existing delegates
1613 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1614 mContext.packageName = RESTRICTIONS_DELEGATE;
1615 try {
1616 dpm.getApplicationRestrictions(null, "pkg");
1617 } catch (SecurityException expected) {
1618 fail("Threw SecurityException on authorized access");
1619 }
1620 }
1621
Esteban Talaverabf60f722015-12-10 16:26:44 +00001622 public void testApplicationRestrictionsManagingApp() throws Exception {
1623 setAsProfileOwner(admin1);
1624
Rubin Xued1928a2016-02-11 17:23:06 +00001625 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001626 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001627 final String nonDelegateExceptionMessageRegex =
1628 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001629 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001630 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1631 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001632
Esteban Talaverabf60f722015-12-10 16:26:44 +00001633 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1634 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001635 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1636 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001637 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001638 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001639 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001640 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1641 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001642
1643 // Check via the profile owner that no restrictions were set.
1644 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001645 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001646 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1647
Rubin Xued1928a2016-02-11 17:23:06 +00001648 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001649 assertExpectException(PackageManager.NameNotFoundException.class,
1650 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1651 () -> dpm.setApplicationRestrictionsManagingPackage(
1652 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001653
Esteban Talaverabf60f722015-12-10 16:26:44 +00001654 // Let appRestrictionsManagerPackage manage app restrictions
1655 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1656 assertEquals(appRestrictionsManagerPackage,
1657 dpm.getApplicationRestrictionsManagingPackage(admin1));
1658
1659 // Now that package should be able to set and retrieve app restrictions.
1660 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001661 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001662 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1663 dpm.setApplicationRestrictions(null, "pkg1", rest);
1664 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1665 assertEquals(1, returned.size(), 1);
1666 assertEquals("Foo1", returned.get("KEY_STRING"));
1667
1668 // The same app running on a separate user shouldn't be able to manage app restrictions.
1669 mContext.binder.callingUid = UserHandle.getUid(
1670 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1671 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001672 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1673 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001674
1675 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1676 // too.
1677 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001678 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001679 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1680 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1681 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1682
1683 // Removing the ability for the package to manage app restrictions.
1684 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1685 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1686 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001687 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001688 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001689 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1690 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001691 }
1692
Makoto Onukia4f11972015-10-01 13:19:58 -07001693 public void testSetUserRestriction_asDo() throws Exception {
1694 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001695 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001696 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1697 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1698
1699 // First, set DO.
1700
1701 // Call from a process on the system user.
1702 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1703
1704 // Make sure admin1 is installed on system user.
1705 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001706
1707 // Call.
1708 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001709 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001710 UserHandle.USER_SYSTEM));
1711
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001712 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001713 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001714 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001715 DpmTestUtils.assertRestrictions(
1716 DpmTestUtils.newRestrictions(defaultRestrictions),
1717 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1718 );
1719 DpmTestUtils.assertRestrictions(
1720 DpmTestUtils.newRestrictions(defaultRestrictions),
1721 dpm.getUserRestrictions(admin1)
1722 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001723 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001724 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001725 MockUtils.checkUserRestrictions(defaultRestrictions),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001726 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001727 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001728 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001729
1730 for (String restriction : defaultRestrictions) {
1731 dpm.clearUserRestriction(admin1, restriction);
1732 }
1733
Esteban Talavera548a04b2016-12-20 15:22:30 +00001734 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001735 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001736
1737 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001738 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001740 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001741 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001743
Makoto Onukia4f11972015-10-01 13:19:58 -07001744 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001745 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001747 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1748 UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001749 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001750 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001751
Makoto Onuki068c54a2015-10-13 14:34:03 -07001752 DpmTestUtils.assertRestrictions(
1753 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001754 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001755 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1756 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001757 DpmTestUtils.assertRestrictions(
1758 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001760 dpm.getUserRestrictions(admin1)
1761 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001762
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001764 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001765 eq(UserHandle.USER_SYSTEM),
1766 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001767 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001769
Makoto Onuki068c54a2015-10-13 14:34:03 -07001770 DpmTestUtils.assertRestrictions(
1771 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1772 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1773 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001774 DpmTestUtils.assertRestrictions(
1775 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1776 dpm.getUserRestrictions(admin1)
1777 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001778
1779 dpm.clearUserRestriction(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(UserHandle.USER_SYSTEM),
1782 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001783 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001784 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001785
Esteban Talavera548a04b2016-12-20 15:22:30 +00001786 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001787
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1789 // DO sets them, the scope is global.
1790 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001791 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001792 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001793 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001794 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001796 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001797 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001798 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799
1800 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1801 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001802 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803
1804 // More tests.
1805 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001806 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001808 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001809 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001810 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001811
1812 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001814 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001816 UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001817 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001818 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001819
1820 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001821 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001822 eq(UserHandle.USER_SYSTEM),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001823 // DISALLOW_CAMERA will be applied globally.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001825 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_CAMERA),
1826 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001827 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001828 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001829
Eric Sandnessca5969d2018-08-10 13:28:46 +01001830 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1831 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1832 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001833
Eric Sandnessca5969d2018-08-10 13:28:46 +01001834 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1835 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836
Eric Sandnessca5969d2018-08-10 13:28:46 +01001837 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1838 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1839 () -> dpm.setCameraDisabled(admin1, true));
1840 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1841
1842 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1843 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1844 () -> dpm.setKeyguardDisabledFeatures(admin1,
1845 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1846 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1847
1848 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1849 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1850 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1851 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1852
1853 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1854 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1855 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1856 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001857 }
1858
1859 public void testSetUserRestriction_asPo() {
1860 setAsProfileOwner(admin1);
1861
Makoto Onuki068c54a2015-10-13 14:34:03 -07001862 DpmTestUtils.assertRestrictions(
1863 DpmTestUtils.newRestrictions(),
1864 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1865 .ensureUserRestrictions()
1866 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001867
1868 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001869 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001870 eq(DpmMockContext.CALLER_USER_HANDLE),
1871 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001872 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001873 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001874
Makoto Onukia4f11972015-10-01 13:19:58 -07001875 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001876 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001877 eq(DpmMockContext.CALLER_USER_HANDLE),
1878 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1879 UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001880 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001881 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001882
Makoto Onuki068c54a2015-10-13 14:34:03 -07001883 DpmTestUtils.assertRestrictions(
1884 DpmTestUtils.newRestrictions(
1885 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1886 UserManager.DISALLOW_OUTGOING_CALLS
1887 ),
1888 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1889 .ensureUserRestrictions()
1890 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001891 DpmTestUtils.assertRestrictions(
1892 DpmTestUtils.newRestrictions(
1893 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1894 UserManager.DISALLOW_OUTGOING_CALLS
1895 ),
1896 dpm.getUserRestrictions(admin1)
1897 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001898
1899 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001900 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001901 eq(DpmMockContext.CALLER_USER_HANDLE),
1902 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001903 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001904 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001905
1906 DpmTestUtils.assertRestrictions(
1907 DpmTestUtils.newRestrictions(
1908 UserManager.DISALLOW_OUTGOING_CALLS
1909 ),
1910 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1911 .ensureUserRestrictions()
1912 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001913 DpmTestUtils.assertRestrictions(
1914 DpmTestUtils.newRestrictions(
1915 UserManager.DISALLOW_OUTGOING_CALLS
1916 ),
1917 dpm.getUserRestrictions(admin1)
1918 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001919
1920 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001921 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001922 eq(DpmMockContext.CALLER_USER_HANDLE),
1923 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001924 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001925 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001926
Makoto Onuki068c54a2015-10-13 14:34:03 -07001927 DpmTestUtils.assertRestrictions(
1928 DpmTestUtils.newRestrictions(),
1929 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1930 .ensureUserRestrictions()
1931 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001932 DpmTestUtils.assertRestrictions(
1933 DpmTestUtils.newRestrictions(),
1934 dpm.getUserRestrictions(admin1)
1935 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001936
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001937 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1938 // though when DO sets them they'll be applied globally.
1939 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001940 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001941 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001942 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001943 eq(DpmMockContext.CALLER_USER_HANDLE),
1944 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1945 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001946 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001947 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001948
1949 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001950 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001951 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001952 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001953 UserManager.DISALLOW_UNMUTE_MICROPHONE, UserManager.DISALLOW_CAMERA),
1954 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001955 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001956
Makoto Onukia4f11972015-10-01 13:19:58 -07001957 // TODO Make sure restrictions are written to the file.
1958 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001959
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001960 public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
1961 setupProfileOwner();
1962
1963 final long ident = mServiceContext.binder.clearCallingIdentity();
1964 configureContextForAccess(mServiceContext, true);
1965
1966 mServiceContext.binder.callingUid =
1967 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
1968 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
1969 try {
1970 runAsCaller(mServiceContext, dpms, dpm -> {
1971 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
1972 });
1973 } finally {
1974 mServiceContext.binder.restoreCallingIdentity(ident);
1975 }
1976
1977 dpm.addUserRestriction(admin1, UserManager.DISALLOW_CONFIG_DATE_TIME);
1978 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1979 eq(DpmMockContext.CALLER_USER_HANDLE),
1980 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CONFIG_DATE_TIME),
1981 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
1982 reset(getServices().userManagerInternal);
1983
1984 dpm.setCameraDisabled(admin1, true);
1985 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
1986 eq(DpmMockContext.CALLER_USER_HANDLE),
1987 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CONFIG_DATE_TIME,
1988 UserManager.DISALLOW_CAMERA),
1989 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
1990 reset(getServices().userManagerInternal);
1991 }
Esteban Talavera548a04b2016-12-20 15:22:30 +00001992
1993 public void testDefaultEnabledUserRestrictions() throws Exception {
1994 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1995 mContext.callerPermissions.add(permission.MANAGE_USERS);
1996 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1997 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1998
1999 // First, set DO.
2000
2001 // Call from a process on the system user.
2002 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2003
2004 // Make sure admin1 is installed on system user.
2005 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2006
2007 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2008 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
2009 UserHandle.USER_SYSTEM));
2010
2011 // Check that the user restrictions that are enabled by default are set. Then unset them.
2012 String[] defaultRestrictions = UserRestrictionsUtils
2013 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
2014 assertTrue(defaultRestrictions.length > 0);
2015 DpmTestUtils.assertRestrictions(
2016 DpmTestUtils.newRestrictions(defaultRestrictions),
2017 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2018 );
2019 DpmTestUtils.assertRestrictions(
2020 DpmTestUtils.newRestrictions(defaultRestrictions),
2021 dpm.getUserRestrictions(admin1)
2022 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002023 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00002024 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00002025 MockUtils.checkUserRestrictions(defaultRestrictions),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002026 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002027 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002028 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002029
2030 for (String restriction : defaultRestrictions) {
2031 dpm.clearUserRestriction(admin1, restriction);
2032 }
2033
2034 assertNoDeviceOwnerRestrictions();
2035
2036 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002037 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002038 initializeDpms();
2039 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2040 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2041
2042 assertNoDeviceOwnerRestrictions();
2043
2044 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
2045 // is set as it wasn't enabled during setDeviceOwner.
2046 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
2047 assertFalse(UserRestrictionsUtils
2048 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
2049 UserRestrictionsUtils
2050 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
2051 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002052 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002053 initializeDpms();
2054 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2055 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2056
2057 DpmTestUtils.assertRestrictions(
2058 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2059 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2060 );
2061 DpmTestUtils.assertRestrictions(
2062 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2063 dpm.getUserRestrictions(admin1)
2064 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002065 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002066 eq(UserHandle.USER_SYSTEM),
2067 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
2068 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002069 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002070 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002071
2072 // Remove the restriction.
2073 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
2074
2075 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
2076 initializeDpms();
2077 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2078 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2079 assertNoDeviceOwnerRestrictions();
2080 } finally {
2081 UserRestrictionsUtils
2082 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
2083 }
2084 }
2085
2086 private void assertNoDeviceOwnerRestrictions() {
2087 DpmTestUtils.assertRestrictions(
2088 DpmTestUtils.newRestrictions(),
2089 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2090 );
2091 DpmTestUtils.assertRestrictions(
2092 DpmTestUtils.newRestrictions(),
2093 dpm.getUserRestrictions(admin1)
2094 );
2095 }
2096
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002097 public void testGetMacAddress() throws Exception {
2098 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2099 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2100 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2101
2102 // In this test, change the caller user to "system".
2103 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2104
2105 // Make sure admin1 is installed on system user.
2106 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2107
2108 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002109 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2110 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002111
2112 // DO needs to be an DA.
2113 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2114 assertTrue(dpm.isAdminActive(admin1));
2115
2116 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002117 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2118 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002119
2120 // Test 3. Caller has PO, but not DO.
2121 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002122 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2123 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002124
2125 // Remove PO.
2126 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002127 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002128 // Test 4, Caller is DO now.
2129 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2130
xshu425b9a62018-12-13 14:18:18 -08002131 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002132 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002133
xshu425b9a62018-12-13 14:18:18 -08002134 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2135 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002136 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002137
2138 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002139 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2140 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002141 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002142 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002143
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002144 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002145 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2146 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2147
2148 // In this test, change the caller user to "system".
2149 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2150
2151 // Make sure admin1 is installed on system user.
2152 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2153
2154 // Set admin1 as DA.
2155 dpm.setActiveAdmin(admin1, false);
2156 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002157 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2158 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002159
2160 // Set admin1 as PO.
2161 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002162 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2163 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002164
2165 // Remove PO and add DO.
2166 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002167 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002168 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2169
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002170 // admin1 is DO.
2171 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002172 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002173 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002174 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2175 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002176
2177 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002178 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002179 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002180 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2181 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002182
2183 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002184 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002185 dpm.reboot(admin1);
2186 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002187
2188 public void testSetGetSupportText() {
2189 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2190 dpm.setActiveAdmin(admin1, true);
2191 dpm.setActiveAdmin(admin2, true);
2192 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2193
2194 // Null default support messages.
2195 {
2196 assertNull(dpm.getLongSupportMessage(admin1));
2197 assertNull(dpm.getShortSupportMessage(admin1));
2198 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2199 assertNull(dpm.getShortSupportMessageForUser(admin1,
2200 DpmMockContext.CALLER_USER_HANDLE));
2201 assertNull(dpm.getLongSupportMessageForUser(admin1,
2202 DpmMockContext.CALLER_USER_HANDLE));
2203 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2204 }
2205
2206 // Only system can call the per user versions.
2207 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002208 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2209 () -> dpm.getShortSupportMessageForUser(admin1,
2210 DpmMockContext.CALLER_USER_HANDLE));
2211 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2212 () -> dpm.getLongSupportMessageForUser(admin1,
2213 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002214 }
2215
2216 // Can't set message for admin in another uid.
2217 {
2218 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002219 assertExpectException(SecurityException.class,
2220 /* messageRegex= */ "is not owned by uid",
2221 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002222 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2223 }
2224
2225 // Set/Get short returns what it sets and other admins text isn't changed.
2226 {
2227 final String supportText = "Some text to test with.";
2228 dpm.setShortSupportMessage(admin1, supportText);
2229 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2230 assertNull(dpm.getLongSupportMessage(admin1));
2231 assertNull(dpm.getShortSupportMessage(admin2));
2232
2233 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2234 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2235 DpmMockContext.CALLER_USER_HANDLE));
2236 assertNull(dpm.getShortSupportMessageForUser(admin2,
2237 DpmMockContext.CALLER_USER_HANDLE));
2238 assertNull(dpm.getLongSupportMessageForUser(admin1,
2239 DpmMockContext.CALLER_USER_HANDLE));
2240 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2241
2242 dpm.setShortSupportMessage(admin1, null);
2243 assertNull(dpm.getShortSupportMessage(admin1));
2244 }
2245
2246 // Set/Get long returns what it sets and other admins text isn't changed.
2247 {
2248 final String supportText = "Some text to test with.\nWith more text.";
2249 dpm.setLongSupportMessage(admin1, supportText);
2250 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2251 assertNull(dpm.getShortSupportMessage(admin1));
2252 assertNull(dpm.getLongSupportMessage(admin2));
2253
2254 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2255 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2256 DpmMockContext.CALLER_USER_HANDLE));
2257 assertNull(dpm.getLongSupportMessageForUser(admin2,
2258 DpmMockContext.CALLER_USER_HANDLE));
2259 assertNull(dpm.getShortSupportMessageForUser(admin1,
2260 DpmMockContext.CALLER_USER_HANDLE));
2261 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2262
2263 dpm.setLongSupportMessage(admin1, null);
2264 assertNull(dpm.getLongSupportMessage(admin1));
2265 }
2266 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002267
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002268 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002269 setAsProfileOwner(admin1);
2270
2271 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002272 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002273
2274 // Setup
2275 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2276 final String package1 = "com.example.one";
2277 final String package2 = "com.example.two";
2278 pkgsToRestrict.add(package1);
2279 pkgsToRestrict.add(package2);
2280 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2281 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002282 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002283
2284 // Verify
2285 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002286 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002287 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2288 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2289 eq(DpmMockContext.CALLER_USER_HANDLE));
2290
2291 // Setup
2292 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002293 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002294
2295 // Verify
2296 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002297 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002298 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2299 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2300 eq(DpmMockContext.CALLER_USER_HANDLE));
2301 }
2302
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002303 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002304 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2305 dpm.setActiveAdmin(admin1, true);
2306 assertTrue(dpm.isAdminActive(admin1));
2307 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2308
2309 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002310 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002311 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002312 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002313 }
2314
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002315 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002316 setAsProfileOwner(admin1);
2317
2318 // Setup
2319 final ArrayList<String> emptyList = new ArrayList<>();
2320 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2321 final String package1 = "com.example.one";
2322 final String package2 = "com.example.two";
2323 final String package3 = "com.example.three";
2324 pkgsToRestrict.add(package1);
2325 pkgsToRestrict.add(package2);
2326 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2327 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002328 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002329
2330 // Verify
2331 assertEquals(emptyList, excludedPkgs);
2332 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2333 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002334 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002335 DpmMockContext.CALLER_USER_HANDLE));
2336 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002337 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002338 DpmMockContext.CALLER_USER_HANDLE));
2339 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002340 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002341 DpmMockContext.CALLER_USER_HANDLE));
2342 }
2343
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002344 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002345 setAsProfileOwner(admin1);
2346 assertExpectException(SecurityException.class,
2347 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002348 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002349 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2350 dpm.clearProfileOwner(admin1);
2351
2352 setDeviceOwner();
2353 assertExpectException(SecurityException.class,
2354 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002355 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002356 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2357 clearDeviceOwner();
2358 }
2359
phweiss73145f42017-01-17 19:06:38 +01002360 public void testCreateAdminSupportIntent() throws Exception {
2361 // Setup device owner.
2362 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2363 setupDeviceOwner();
2364
2365 // Nonexisting permission returns null
2366 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2367 assertNull(intent);
2368
2369 // Existing permission that is not set returns null
2370 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2371 assertNull(intent);
2372
2373 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002374 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002375 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2376 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2377 .thenReturn(true);
2378 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2379 assertNull(intent);
2380
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002381 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2382 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2383 new UserManager.EnforcingUser(
2384 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2385 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002386 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002387 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002388 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2389 assertNotNull(intent);
2390 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2391 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2392 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002393 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002394 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2395 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2396
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002397 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2398 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002399
2400 // Camera is not disabled
2401 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2402 assertNull(intent);
2403
2404 // Camera is disabled
2405 dpm.setCameraDisabled(admin1, true);
2406 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2407 assertNotNull(intent);
2408 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2409 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2410
2411 // Screen capture is not disabled
2412 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2413 assertNull(intent);
2414
2415 // Screen capture is disabled
2416 dpm.setScreenCaptureDisabled(admin1, true);
2417 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2418 assertNotNull(intent);
2419 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2420 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2421
2422 // Same checks for different user
2423 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2424 // Camera should be disabled by device owner
2425 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2426 assertNotNull(intent);
2427 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2428 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2429 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2430 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2431 // ScreenCapture should not be disabled by device owner
2432 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2433 assertNull(intent);
2434 }
2435
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002436 /**
2437 * Test for:
2438 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002439 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002440 * {@link DevicePolicyManager#isAffiliatedUser}
2441 */
2442 public void testUserAffiliation() throws Exception {
2443 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2444 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2445 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2446
2447 // Check that the system user is unaffiliated.
2448 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2449 assertFalse(dpm.isAffiliatedUser());
2450
2451 // Set a device owner on the system user. Check that the system user becomes affiliated.
2452 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2453 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2454 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2455 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002456 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002457
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002458 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002459 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2460 setAsProfileOwner(admin2);
2461 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002462 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002463
2464 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2465 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002466 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002467 userAffiliationIds.add("red");
2468 userAffiliationIds.add("green");
2469 userAffiliationIds.add("blue");
2470 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002471 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002472 assertFalse(dpm.isAffiliatedUser());
2473
2474 // Have the device owner specify a set of affiliation ids that do not intersect with those
2475 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002476 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002477 deviceAffiliationIds.add("cyan");
2478 deviceAffiliationIds.add("yellow");
2479 deviceAffiliationIds.add("magenta");
2480 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2481 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002482 MoreAsserts.assertContentsInAnyOrder(
2483 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002484 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2485 assertFalse(dpm.isAffiliatedUser());
2486
2487 // Have the profile owner specify a set of affiliation ids that intersect with those
2488 // specified by the device owner. Check that the test user becomes affiliated.
2489 userAffiliationIds.add("yellow");
2490 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002491 MoreAsserts.assertContentsInAnyOrder(
2492 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002493 assertTrue(dpm.isAffiliatedUser());
2494
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002495 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002496 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002497 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002498 assertFalse(dpm.isAffiliatedUser());
2499
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002500 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2501 dpm.setAffiliationIds(admin2, userAffiliationIds);
2502 assertTrue(dpm.isAffiliatedUser());
2503 dpm.clearProfileOwner(admin2);
2504 assertFalse(dpm.isAffiliatedUser());
2505
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002506 // Check that the system user remains affiliated.
2507 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2508 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002509
2510 // Clear the device owner - the user becomes unaffiliated.
2511 clearDeviceOwner();
2512 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002513 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002514
2515 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002516 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002517 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2518 }
2519
2520 public void testSetUserProvisioningState_permission() throws Exception {
2521 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002522
2523 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2524 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2525 }
2526
2527 public void testSetUserProvisioningState_unprivileged() throws Exception {
2528 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002529 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2530 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2531 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002532 }
2533
2534 public void testSetUserProvisioningState_noManagement() {
2535 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002536 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002537 assertExpectException(IllegalStateException.class,
2538 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2539 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2540 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002541 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2542 }
2543
2544 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2545 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2546 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002547
2548 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2549 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2550 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2551 }
2552
2553 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2554 throws Exception {
2555 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2556 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002557
2558 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2559 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2560 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2561 }
2562
2563 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2564 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2565 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002566
2567 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2568 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2569 }
2570
2571 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2572 throws Exception {
2573 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002574
2575 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2576 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2577 DevicePolicyManager.STATE_USER_UNMANAGED);
2578 }
2579
2580 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2581 throws Exception {
2582 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002583
2584 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2585 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2586 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2587 }
2588
2589 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2590 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002591
2592 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2593 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2594 }
2595
2596 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2597 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002598
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002599 assertExpectException(IllegalStateException.class,
2600 /* messageRegex= */ "Cannot move to user provisioning state",
2601 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2602 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2603 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002604 }
2605
2606 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2607 throws Exception {
2608 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002609
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002610 assertExpectException(IllegalStateException.class,
2611 /* messageRegex= */ "Cannot move to user provisioning state",
2612 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2613 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2614 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002615 }
2616
2617 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002618 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2619 mContext.callerPermissions.add(permission.MANAGE_USERS);
2620
Alan Treadwayafad8782016-01-19 15:15:08 +00002621 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2622 for (int state : states) {
2623 dpm.setUserProvisioningState(state, userId);
2624 assertEquals(state, dpm.getUserProvisioningState());
2625 }
2626 }
2627
2628 private void setupProfileOwner() throws Exception {
2629 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2630
2631 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2632 dpm.setActiveAdmin(admin1, false);
2633 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2634
2635 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2636 }
2637
2638 private void setupDeviceOwner() throws Exception {
2639 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2640
2641 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2642 dpm.setActiveAdmin(admin1, false);
2643 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2644
2645 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2646 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002647
2648 public void testSetMaximumTimeToLock() {
2649 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2650
2651 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2652 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2653
Pavel Grafov75c0a892017-05-18 17:28:27 +01002654 reset(getServices().powerManagerInternal);
2655 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002656
2657 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002658 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2659 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002660 reset(getServices().powerManagerInternal);
2661 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002662
2663 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002664 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2665 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002666 reset(getServices().powerManagerInternal);
2667 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002668
2669 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002670 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2671 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002672 reset(getServices().powerManagerInternal);
2673 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002674
2675 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002676 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2677 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002678 reset(getServices().powerManagerInternal);
2679 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002680
2681 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002682 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2683 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002684 reset(getServices().powerManagerInternal);
2685 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002686
2687 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002688 reset(getServices().powerManagerInternal);
2689 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002690
Pavel Grafov28939982017-10-03 15:11:52 +01002691 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2692 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2693 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002694 reset(getServices().powerManagerInternal);
2695 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002696
2697 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002698 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2699 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002700 reset(getServices().powerManagerInternal);
2701 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002702
Pavel Grafov28939982017-10-03 15:11:52 +01002703 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002704 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002705 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2706 verifyStayOnWhilePluggedCleared(false);
2707 }
2708
Varun Shahb472b8f2019-09-23 23:01:06 -07002709 public void testIsActiveSupervisionApp() throws Exception {
2710 when(mServiceContext.resources
2711 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2712 .thenReturn(admin1.flattenToString());
2713
2714 final int PROFILE_USER = 15;
2715 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2716 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2717 mContext.binder.callingUid = PROFILE_ADMIN;
2718
2719 final DevicePolicyManagerInternal dpmi =
2720 LocalServices.getService(DevicePolicyManagerInternal.class);
2721 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2722 }
2723
Pavel Grafov28939982017-10-03 15:11:52 +01002724 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2725 // uses separate challenge.
2726 public void testSetMaximumTimeToLockProfile() throws Exception {
2727 final int PROFILE_USER = 15;
2728 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2729 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2730 mContext.binder.callingUid = PROFILE_ADMIN;
2731 final DevicePolicyManagerInternal dpmi =
2732 LocalServices.getService(DevicePolicyManagerInternal.class);
2733
2734 dpm.setMaximumTimeToLock(admin1, 0);
2735
2736 reset(getServices().powerManagerInternal);
2737 reset(getServices().settings);
2738
2739 // First add timeout for the profile.
2740 dpm.setMaximumTimeToLock(admin1, 10);
2741 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2742
2743 reset(getServices().powerManagerInternal);
2744 reset(getServices().settings);
2745
2746 // Add separate challenge
2747 when(getServices().lockPatternUtils
2748 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2749 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2750
2751 verifyScreenTimeoutCall(10L, PROFILE_USER);
2752 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2753
2754 reset(getServices().powerManagerInternal);
2755 reset(getServices().settings);
2756
2757 // Remove the timeout.
2758 dpm.setMaximumTimeToLock(admin1, 0);
2759 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2760 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2761
2762 reset(getServices().powerManagerInternal);
2763 reset(getServices().settings);
2764
2765 // Add it back.
2766 dpm.setMaximumTimeToLock(admin1, 10);
2767 verifyScreenTimeoutCall(10L, PROFILE_USER);
2768 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2769
2770 reset(getServices().powerManagerInternal);
2771 reset(getServices().settings);
2772
2773 // Remove separate challenge.
2774 reset(getServices().lockPatternUtils);
2775 when(getServices().lockPatternUtils
2776 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2777 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002778 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002779
2780 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2781 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2782
2783 reset(getServices().powerManagerInternal);
2784 reset(getServices().settings);
2785
2786 // Remove the timeout.
2787 dpm.setMaximumTimeToLock(admin1, 0);
2788 verifyScreenTimeoutCall(null, PROFILE_USER);
2789 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002790 }
2791
Michal Karpinski943aabd2016-10-06 11:09:25 +01002792 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2793 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2794 setupDeviceOwner();
2795 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2796
Michal Karpinskid084ca52017-01-18 15:54:18 +00002797 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2798 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2799 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2800 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2801 - ONE_MINUTE;
2802
2803 // verify that the minimum timeout cannot be modified on user builds (system property is
2804 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002805 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002806
2807 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2808 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2809 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2810
Pavel Grafov75c0a892017-05-18 17:28:27 +01002811 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002812
2813 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002814 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002815
Michal Karpinskid084ca52017-01-18 15:54:18 +00002816 // reset to default (0 means the admin is not participating, so default should be returned)
2817 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002818
2819 // aggregation should be the default if unset by any admin
2820 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2821 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2822
2823 // admin not participating by default
2824 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2825
2826 //clamping from the top
2827 dpm.setRequiredStrongAuthTimeout(admin1,
2828 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2829 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2830 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2831 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2832 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2833
Michal Karpinskid084ca52017-01-18 15:54:18 +00002834 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002835 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2836 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2837 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2838 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2839
2840 // clamping from the bottom
2841 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2842 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2843 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2844
Michal Karpinskid084ca52017-01-18 15:54:18 +00002845 // values within range
2846 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2847 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2848 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2849
2850 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2851 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2852 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002853
2854 // reset to default
2855 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2856 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2857 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2858 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2859
2860 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002861 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2862 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002863 }
2864
Pavel Grafov28939982017-10-03 15:11:52 +01002865 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002866 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002867 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002868 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002869 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002870 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002871 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002872 }
Pavel Grafov28939982017-10-03 15:11:52 +01002873 }
2874
2875 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002876 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2877 // UnfinishedVerificationException.
2878 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002879
Esteban Talavera01576862016-12-15 11:16:44 +00002880 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002881 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002882 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002883 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002884 .thenReturn(false);
2885 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002886 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2887 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002888 .thenReturn(true);
2889 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2890
2891 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002892 }
Victor Chang3e794af2016-03-04 13:48:17 +00002893
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002894 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2895 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002896 mContext.packageName = admin1.getPackageName();
2897 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002898 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2899 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2900 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2901 false);
2902 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2903 }
2904
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002905 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2906 setup_DeviceAdminFeatureOff();
2907 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2908 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2909 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2910 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2911 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2912 assertCheckProvisioningPreCondition(
2913 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2914 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2915 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2916 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2917 }
2918
Esteban Talavera01576862016-12-15 11:16:44 +00002919 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002920 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002921 .thenReturn(false);
2922 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002923 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2924 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002925 .thenReturn(true);
2926 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2927
2928 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002929 }
Victor Chang3e794af2016-03-04 13:48:17 +00002930
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002931 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2932 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002933 mContext.packageName = admin1.getPackageName();
2934 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002935 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2938 false);
2939 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2940
2941 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002942 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002943 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2944 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2945 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2946 true);
2947 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2948 }
2949
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002950 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2951 setup_ManagedProfileFeatureOff();
2952 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2953 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2954 DevicePolicyManager.CODE_OK);
2955 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2956 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2957 assertCheckProvisioningPreCondition(
2958 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2959 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2960 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2961 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2962
2963 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002964 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002965 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2966 DevicePolicyManager.CODE_OK);
2967 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2968 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2969 assertCheckProvisioningPreCondition(
2970 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2971 DevicePolicyManager.CODE_OK);
2972 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2973 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2974 }
2975
Esteban Talavera01576862016-12-15 11:16:44 +00002976 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002977 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002978 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002979 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2980 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002981 .thenReturn(true);
2982 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2983
2984 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002985 }
Victor Chang3e794af2016-03-04 13:48:17 +00002986
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002987 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2988 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002989 mContext.packageName = admin1.getPackageName();
2990 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002991 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2992 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2993 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2994 false /* because of non-split user */);
2995 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2996 false /* because of non-split user */);
2997 }
2998
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002999 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003000 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003001 setup_nonSplitUser_firstBoot_primaryUser();
3002 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3003 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3004 DevicePolicyManager.CODE_OK);
3005 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3006 DevicePolicyManager.CODE_OK);
3007 assertCheckProvisioningPreCondition(
3008 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3009 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3010 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3011 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3012 }
3013
Esteban Talavera01576862016-12-15 11:16:44 +00003014 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003015 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003016 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003017 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3018 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003019 .thenReturn(true);
3020 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3021
3022 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003023 }
Victor Chang3e794af2016-03-04 13:48:17 +00003024
Nicolas Prevot45d29072017-01-18 16:11:19 +00003025 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
3026 setDeviceOwner();
3027 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3028 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3029 }
3030
3031 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3032 setup_nonSplitUser_withDo_primaryUser();
3033 final int MANAGED_PROFILE_USER_ID = 18;
3034 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
3035 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003036 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003037 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003039 true)).thenReturn(true);
3040 }
3041
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003042 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3043 throws Exception {
3044 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003045 mContext.packageName = admin1.getPackageName();
3046 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003047 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3048 false/* because of completed device setup */);
3049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3050 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3051 false/* because of non-split user */);
3052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3053 false/* because of non-split user */);
3054 }
3055
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003056 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3057 throws Exception {
3058 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3059 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3060 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3061 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3062 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3063 DevicePolicyManager.CODE_OK);
3064 assertCheckProvisioningPreCondition(
3065 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3066 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3067 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3068 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3069 }
3070
Nicolas Prevot45d29072017-01-18 16:11:19 +00003071 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3072 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003073 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003074 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3075
3076 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3077 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003079
3080 // COMP mode is allowed.
3081 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3082 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003083 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003084
Nicolas Prevot45d29072017-01-18 16:11:19 +00003085 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003086 assertCheckProvisioningPreCondition(
3087 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003088 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003089 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003090 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3091 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3092 }
Esteban Talavera01576862016-12-15 11:16:44 +00003093
Nicolas Prevot45d29072017-01-18 16:11:19 +00003094 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3095 setup_nonSplitUser_withDo_primaryUser();
3096 mContext.packageName = admin1.getPackageName();
3097 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3098 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3099 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003100 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003101 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3102 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3103 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003104 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003105 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3106 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3107 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3108 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3109 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003111 assertCheckProvisioningPreCondition(
3112 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003113 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003114 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003115 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3116 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3117 }
Esteban Talavera01576862016-12-15 11:16:44 +00003118
Nicolas Prevot45d29072017-01-18 16:11:19 +00003119 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3120 throws Exception {
3121 setup_nonSplitUser_withDo_primaryUser();
3122 mContext.packageName = admin1.getPackageName();
3123 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003124 // The DO should not be allowed to initiate provisioning if the restriction is set by
3125 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003126 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003127 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3128 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3129 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003130 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003131 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3132 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3133 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3134 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3135 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003136 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3137
3138 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003139 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003140 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003141 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003142 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3143 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3144 }
3145
3146 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3147 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3148 mContext.packageName = admin1.getPackageName();
3149 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3150
3151 // We can delete the managed profile to create a new one, so provisioning is allowed.
3152 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3153 DevicePolicyManager.CODE_OK);
3154 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3155 assertCheckProvisioningPreCondition(
3156 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3157 DpmMockContext.ANOTHER_PACKAGE_NAME,
3158 DevicePolicyManager.CODE_OK);
3159 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3160 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3161 }
3162
3163 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3164 throws Exception {
3165 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3166 mContext.packageName = admin1.getPackageName();
3167 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003168 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003169 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3170 eq(UserHandle.SYSTEM)))
3171 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003172 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003173 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3174 eq(UserHandle.SYSTEM)))
3175 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003176
3177 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003178 assertCheckProvisioningPreCondition(
3179 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3180 DpmMockContext.ANOTHER_PACKAGE_NAME,
3181 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3182 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3183 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003184
3185 // But the device owner can still do it because it has set the restriction itself.
3186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3187 DevicePolicyManager.CODE_OK);
3188 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003189 }
3190
3191 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003192 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003193 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003194 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3195 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003196 .thenReturn(false);
3197 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3198
3199 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003200 }
Victor Chang3e794af2016-03-04 13:48:17 +00003201
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003202 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3203 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003204 mContext.packageName = admin1.getPackageName();
3205 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003206 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3207 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3208 false /* because canAddMoreManagedProfiles returns false */);
3209 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3210 true);
3211 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3212 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003213 }
3214
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003215 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3216 throws Exception {
3217 setup_splitUser_firstBoot_systemUser();
3218 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3219 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3220 DevicePolicyManager.CODE_OK);
3221 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003222 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003223 assertCheckProvisioningPreCondition(
3224 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3225 DevicePolicyManager.CODE_OK);
3226 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3227 DevicePolicyManager.CODE_SYSTEM_USER);
3228 }
3229
Esteban Talavera01576862016-12-15 11:16:44 +00003230 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003231 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003232 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003233 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3234 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003235 .thenReturn(false);
3236 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3237
3238 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003239 }
Victor Chang3e794af2016-03-04 13:48:17 +00003240
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003241 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3242 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003243 mContext.packageName = admin1.getPackageName();
3244 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003245 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3246 true/* it's undefined behavior. Can be changed into false in the future */);
3247 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3248 false /* because canAddMoreManagedProfiles returns false */);
3249 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3250 true/* it's undefined behavior. Can be changed into false in the future */);
3251 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3252 false/* because calling uid is system user */);
3253 }
3254
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003255 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3256 throws Exception {
3257 setup_splitUser_afterDeviceSetup_systemUser();
3258 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3259 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3260 DevicePolicyManager.CODE_OK);
3261 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003262 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003263 assertCheckProvisioningPreCondition(
3264 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3265 DevicePolicyManager.CODE_OK);
3266 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3267 DevicePolicyManager.CODE_SYSTEM_USER);
3268 }
3269
Esteban Talavera01576862016-12-15 11:16:44 +00003270 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003271 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003272 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003273 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3274 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003275 true)).thenReturn(true);
3276 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3277
3278 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003279 }
Victor Chang3e794af2016-03-04 13:48:17 +00003280
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003281 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3282 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003283 mContext.packageName = admin1.getPackageName();
3284 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003285 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3286 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3287 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3288 true);
3289 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003290 }
3291
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003292 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003293 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 setup_splitUser_firstBoot_primaryUser();
3295 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3296 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3297 DevicePolicyManager.CODE_OK);
3298 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3299 DevicePolicyManager.CODE_OK);
3300 assertCheckProvisioningPreCondition(
3301 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3302 DevicePolicyManager.CODE_OK);
3303 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3304 DevicePolicyManager.CODE_OK);
3305 }
3306
Esteban Talavera01576862016-12-15 11:16:44 +00003307 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003308 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003309 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003310 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3311 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003312 true)).thenReturn(true);
3313 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3314
3315 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003316 }
Victor Chang3e794af2016-03-04 13:48:17 +00003317
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003318 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3319 throws Exception {
3320 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003321 mContext.packageName = admin1.getPackageName();
3322 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003323 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3324 true/* it's undefined behavior. Can be changed into false in the future */);
3325 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3326 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3327 true/* it's undefined behavior. Can be changed into false in the future */);
3328 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3329 false/* because user setup completed */);
3330 }
3331
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003332 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003333 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003334 setup_splitUser_afterDeviceSetup_primaryUser();
3335 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3336 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3337 DevicePolicyManager.CODE_OK);
3338 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3339 DevicePolicyManager.CODE_OK);
3340 assertCheckProvisioningPreCondition(
3341 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3342 DevicePolicyManager.CODE_OK);
3343 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3344 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3345 }
3346
Esteban Talavera01576862016-12-15 11:16:44 +00003347 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003348 setDeviceOwner();
3349
Pavel Grafov75c0a892017-05-18 17:28:27 +01003350 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003351 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003352 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3353 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003354 .thenReturn(false);
3355 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3356
3357 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003358 }
Victor Chang3e794af2016-03-04 13:48:17 +00003359
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003360 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3361 throws Exception {
3362 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003363 mContext.packageName = admin1.getPackageName();
3364 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003365 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3366 false /* can't provision managed profile on system user */);
3367 }
3368
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003369 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003370 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003371 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3372 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3373 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3374 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3375 }
3376
3377 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003378 setDeviceOwner();
3379
Pavel Grafov75c0a892017-05-18 17:28:27 +01003380 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003381 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003382 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3383 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003384 true)).thenReturn(true);
3385 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3386
3387 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003388 }
Victor Chang3e794af2016-03-04 13:48:17 +00003389
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003390 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3391 throws Exception {
3392 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003393 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3394 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003395 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3396 }
3397
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003398 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003399 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003400 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3401 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003402
3403 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003404 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3405 DevicePolicyManager.CODE_OK);
3406 }
3407
3408 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003409 setDeviceOwner();
3410
Pavel Grafov75c0a892017-05-18 17:28:27 +01003411 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003412 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003413 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3414 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003415 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3416 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003417 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003418 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003419 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003420 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003421 true)).thenReturn(true);
3422 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3423
3424 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003425 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003426
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003427 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3428 throws Exception {
3429 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003430 mContext.packageName = admin1.getPackageName();
3431 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003432 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3433 }
3434
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003435 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3436 throws Exception {
3437 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3438 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3439 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3440 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3441 }
3442
3443 public void testCheckProvisioningPreCondition_permission() {
3444 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003445 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3446 () -> dpm.checkProvisioningPreCondition(
3447 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003448 }
3449
Victor Chang3577ed22016-08-25 18:49:26 +01003450 public void testForceUpdateUserSetupComplete_permission() {
3451 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003452 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3453 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003454 }
3455
3456 public void testForceUpdateUserSetupComplete_systemUser() {
3457 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3458 // GIVEN calling from user 20
3459 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003460 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3461 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003462 }
3463
3464 public void testForceUpdateUserSetupComplete_userbuild() {
3465 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3466 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3467
3468 final int userId = UserHandle.USER_SYSTEM;
3469 // GIVEN userComplete is false in SettingsProvider
3470 setUserSetupCompleteForUser(false, userId);
3471
3472 // GIVEN userComplete is true in DPM
3473 DevicePolicyManagerService.DevicePolicyData userData =
3474 new DevicePolicyManagerService.DevicePolicyData(userId);
3475 userData.mUserSetupComplete = true;
3476 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3477
3478 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003479 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003480
3481 assertTrue(dpms.hasUserSetupCompleted());
3482
3483 dpm.forceUpdateUserSetupComplete();
3484
3485 // THEN the state in dpms is not changed
3486 assertTrue(dpms.hasUserSetupCompleted());
3487 }
3488
3489 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3490 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3491 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3492
3493 final int userId = UserHandle.USER_SYSTEM;
3494 // GIVEN userComplete is false in SettingsProvider
3495 setUserSetupCompleteForUser(false, userId);
3496
3497 // GIVEN userComplete is true in DPM
3498 DevicePolicyManagerService.DevicePolicyData userData =
3499 new DevicePolicyManagerService.DevicePolicyData(userId);
3500 userData.mUserSetupComplete = true;
3501 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3502
3503 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003504 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003505
3506 assertTrue(dpms.hasUserSetupCompleted());
3507
3508 dpm.forceUpdateUserSetupComplete();
3509
3510 // THEN the state in dpms is not changed
3511 assertFalse(dpms.hasUserSetupCompleted());
3512 }
3513
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003514 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003515 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003516 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003517
3518 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3519 runAsCaller(mAdmin1Context, dpms, dpm -> {
3520 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3521 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003522 }
3523
3524 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3525 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3526 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003527
3528 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3529 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003530 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003531 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3532 .thenReturn(true);
3533
3534 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003535 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003536
3537 // Enabling logging should not change the timestamp.
3538 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003539 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003540 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003541 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003542 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003543 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003544
3545 // Retrieving the logs should update the timestamp.
3546 final long beforeRetrieval = System.currentTimeMillis();
3547 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003548 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003549 final long afterRetrieval = System.currentTimeMillis();
3550 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3551 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3552
3553 // Retrieving the pre-boot logs should update the timestamp.
3554 Thread.sleep(2);
3555 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003556 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003557 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3558
3559 // Checking the timestamp again should not change it.
3560 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003561 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003562
3563 // Retrieving the logs again should update the timestamp.
3564 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003565 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003566 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3567
3568 // Disabling logging should not change the timestamp.
3569 Thread.sleep(2);
3570 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003571 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003572
3573 // Restarting the DPMS should not lose the timestamp.
3574 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003575 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003576
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003577 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3578 mContext.binder.callingUid = 1234567;
3579 mContext.callerPermissions.add(permission.MANAGE_USERS);
3580 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3581 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3582
3583 // System can retrieve the timestamp.
3584 mContext.binder.clearCallingIdentity();
3585 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3586
3587 // Removing the device owner should clear the timestamp.
3588 clearDeviceOwner();
3589 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003590 }
3591
yuemingw0de748d2017-11-15 19:22:27 +00003592 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3593 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3594 setupDeviceOwner();
3595 assertExpectException(SecurityException.class, null, () ->
3596 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3597 }
3598
yuemingwc0281f12018-03-28 15:58:49 +01003599 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003600 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3601 setupDeviceOwner();
3602 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003603 verify(getServices().settings).settingsSystemPutStringForUser(
3604 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3605 }
3606
3607 public void testSetSystemSettingWithPO() throws Exception {
3608 setupProfileOwner();
3609 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3610 verify(getServices().settings).settingsSystemPutStringForUser(
3611 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003612 }
3613
yuemingwe43cdf72017-10-12 16:52:11 +01003614 public void testSetTime() throws Exception {
3615 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3616 setupDeviceOwner();
3617 dpm.setTime(admin1, 0);
Neil Fullere3767562019-11-23 11:33:57 +00003618
3619 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3620 @Override
3621 public boolean matches(Object item) {
3622 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3623 return suggestion.getUtcTime().getValue() == 0;
3624 }
3625 @Override
3626 public void describeTo(Description description) {
3627 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3628 }
3629 };
3630 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
yuemingwe43cdf72017-10-12 16:52:11 +01003631 }
3632
3633 public void testSetTimeFailWithPO() throws Exception {
3634 setupProfileOwner();
3635 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3636 }
3637
3638 public void testSetTimeWithAutoTimeOn() throws Exception {
3639 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3640 setupDeviceOwner();
3641 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3642 .thenReturn(1);
3643 assertFalse(dpm.setTime(admin1, 0));
3644 }
3645
3646 public void testSetTimeZone() throws Exception {
3647 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3648 setupDeviceOwner();
3649 dpm.setTimeZone(admin1, "Asia/Shanghai");
3650 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3651 }
3652
3653 public void testSetTimeZoneFailWithPO() throws Exception {
3654 setupProfileOwner();
3655 assertExpectException(SecurityException.class, null,
3656 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3657 }
3658
3659 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3660 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3661 setupDeviceOwner();
3662 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3663 .thenReturn(1);
3664 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3665 }
3666
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003667 public void testGetLastBugReportRequestTime() throws Exception {
3668 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3669 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003670
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003671 mContext.packageName = admin1.getPackageName();
3672 mContext.applicationInfo = new ApplicationInfo();
3673 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3674 .thenReturn(Color.WHITE);
3675 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3676 anyObject())).thenReturn(Color.WHITE);
3677
Esteban Talaverad36dd152016-12-15 08:51:45 +00003678 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3679 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003680 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003681
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003682 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003683 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003684
3685 // Requesting a bug report should update the timestamp.
3686 final long beforeRequest = System.currentTimeMillis();
3687 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003688 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003689 final long afterRequest = System.currentTimeMillis();
3690 assertTrue(bugReportRequestTime >= beforeRequest);
3691 assertTrue(bugReportRequestTime <= afterRequest);
3692
3693 // Checking the timestamp again should not change it.
3694 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003695 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003696
3697 // Restarting the DPMS should not lose the timestamp.
3698 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003699 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003700
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003701 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3702 mContext.binder.callingUid = 1234567;
3703 mContext.callerPermissions.add(permission.MANAGE_USERS);
3704 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3705 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3706
3707 // System can retrieve the timestamp.
3708 mContext.binder.clearCallingIdentity();
3709 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3710
3711 // Removing the device owner should clear the timestamp.
3712 clearDeviceOwner();
3713 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003714 }
3715
3716 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3717 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3718 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003719 mContext.packageName = admin1.getPackageName();
3720 mContext.applicationInfo = new ApplicationInfo();
3721 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3722 .thenReturn(Color.WHITE);
3723 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3724 anyObject())).thenReturn(Color.WHITE);
3725
3726 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3727 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003728 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003729 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003730 .thenReturn(true);
3731
3732 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003733 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003734
3735 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3736 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003737 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003738
3739 // Enabling logging should not change the timestamp.
3740 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003741 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003742
3743 // Retrieving the logs should update the timestamp.
3744 final long beforeRetrieval = System.currentTimeMillis();
3745 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003746 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003747 final long afterRetrieval = System.currentTimeMillis();
3748 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3749 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3750
3751 // Checking the timestamp again should not change it.
3752 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003753 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003754
3755 // Retrieving the logs again should update the timestamp.
3756 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003757 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003758 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3759
3760 // Disabling logging should not change the timestamp.
3761 Thread.sleep(2);
3762 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003763 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003764
3765 // Restarting the DPMS should not lose the timestamp.
3766 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003767 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3768
3769 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3770 mContext.binder.callingUid = 1234567;
3771 mContext.callerPermissions.add(permission.MANAGE_USERS);
3772 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3773 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3774
3775 // System can retrieve the timestamp.
3776 mContext.binder.clearCallingIdentity();
3777 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3778
3779 // Removing the device owner should clear the timestamp.
3780 clearDeviceOwner();
3781 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003782 }
3783
Tony Mak2f26b792016-11-28 17:54:51 +00003784 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3785 // Setup device owner.
3786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3787 setupDeviceOwner();
3788
3789 // Only device owner is setup, the result list should be empty.
3790 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3791 MoreAsserts.assertEmpty(targetUsers);
3792
3793 // Setup a managed profile managed by the same admin.
3794 final int MANAGED_PROFILE_USER_ID = 15;
3795 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3796 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3797
3798 // Add a secondary user, it should never talk with.
3799 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003800 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003801
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003802 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3803 // other.
3804 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3805 MoreAsserts.assertEmpty(targetUsers);
3806
3807 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3808 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3809 MoreAsserts.assertEmpty(targetUsers);
3810
3811 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003812 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003813 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3814 dpm.setAffiliationIds(admin1, userAffiliationIds);
3815
3816 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3817 dpm.setAffiliationIds(admin1, userAffiliationIds);
3818
Tony Mak2f26b792016-11-28 17:54:51 +00003819 // Calling from device owner admin, the result list should just contain the managed
3820 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003822 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3823 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3824
3825 // Calling from managed profile admin, the result list should just contain the system
3826 // user id.
3827 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3828 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3829 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003830
3831 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003832 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003833
3834 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3835 // to each other.
3836 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3837 MoreAsserts.assertEmpty(targetUsers);
3838
3839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3840 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3841 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003842 }
3843
3844 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3845 // Setup a device owner.
3846 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3847 setupDeviceOwner();
3848
3849 // Set up a managed profile managed by different package.
3850 final int MANAGED_PROFILE_USER_ID = 15;
3851 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3852 final ComponentName adminDifferentPackage =
3853 new ComponentName("another.package", "whatever.class");
3854 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3855
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003856 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003857 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003858 dpm.setAffiliationIds(admin1, userAffiliationIds);
3859
3860 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3861 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3862
Tony Mak2f26b792016-11-28 17:54:51 +00003863 // Calling from device owner admin, we should get zero bind device admin target users as
3864 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003866 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3867 MoreAsserts.assertEmpty(targetUsers);
3868
3869 // Calling from managed profile admin, we should still get zero target users for the same
3870 // reason.
3871 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3872 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3873 MoreAsserts.assertEmpty(targetUsers);
3874 }
3875
Jason Parks3c13b642017-11-28 15:39:43 -06003876 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003877 verifyLockTaskState(userId, new String[0],
3878 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003879 }
3880
3881 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3882 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003883 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003884 }
3885
3886 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3887 int flags) throws Exception {
3888 mContext.binder.callingUid = uid;
3889 dpm.setLockTaskPackages(who, packages);
3890 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3891 for (String p : packages) {
3892 assertTrue(dpm.isLockTaskPermitted(p));
3893 }
3894 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3895 // Test to see if set lock task features can be set
3896 dpm.setLockTaskFeatures(who, flags);
3897 verifyLockTaskState(userId, packages, flags);
3898 }
3899
3900 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3901 int flags) throws Exception {
3902 mContext.binder.callingUid = uid;
3903 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3904 () -> dpm.setLockTaskPackages(who, packages));
3905 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3906 () -> dpm.getLockTaskPackages(who));
3907 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3908 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3909 () -> dpm.setLockTaskFeatures(who, flags));
3910 }
3911
Charles Hee078db72017-10-19 18:03:20 +01003912 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003913 // Setup a device owner.
3914 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3915 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003916 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003917 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003918
3919 // Set up a managed profile managed by different package (package name shouldn't matter)
3920 final int MANAGED_PROFILE_USER_ID = 15;
3921 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3922 final ComponentName adminDifferentPackage =
3923 new ComponentName("another.package", "whatever.class");
3924 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003925 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3926
3927 // Setup a PO on the secondary user
3928 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3929 setAsProfileOwner(admin3);
3930 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003931
3932 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003933 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003934 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003935 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3936 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003937 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3938
3939 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3940 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003941 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3942 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003943 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003944
3945 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3946 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3947 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003948 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003949 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3950 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003951 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003952
3953 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003954 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003955 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3956 dpm.setAffiliationIds(admin1, userAffiliationIds);
3957
3958 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3959 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3960
3961 // Now the managed profile can set lock task packages.
3962 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3963 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3964 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3965 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003966 // And it can set lock task features.
3967 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003968 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003969
3970 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003971 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003972 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3973 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003974 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3975 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003976 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003977 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003978
Jason Parks3c13b642017-11-28 15:39:43 -06003979 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003980 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3981 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003982
3983 }
3984
3985 public void testLockTaskPolicyForProfileOwner() throws Exception {
3986 // Setup a PO
3987 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3988 setAsProfileOwner(admin1);
3989 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3990
3991 final String[] poPackages = {"poPackage1", "poPackage2"};
3992 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003993 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3994 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003995 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3996 poPackages, poFlags);
3997
3998 // Set up a managed profile managed by different package (package name shouldn't matter)
3999 final int MANAGED_PROFILE_USER_ID = 15;
4000 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
4001 final ComponentName adminDifferentPackage =
4002 new ComponentName("another.package", "whatever.class");
4003 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
4004 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
4005
4006 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
4007 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4008 final String[] mpoPackages = {"poPackage1", "poPackage2"};
4009 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004010 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4011 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004012 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00004013 }
4014
Benjamin Franzcaffa772018-02-05 16:36:10 +00004015 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
4016 // Setup a device owner.
4017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4018 setupDeviceOwner();
4019 // Lock task policy is updated when loading user data.
4020 verifyLockTaskState(UserHandle.USER_SYSTEM);
4021
4022 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4023 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4024 assertExpectException(IllegalArgumentException.class,
4025 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4026 () -> dpm.setLockTaskFeatures(admin1, flags));
4027 }
4028
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01004029 public void testIsDeviceManaged() throws Exception {
4030 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4031 setupDeviceOwner();
4032
4033 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
4034 // find out that the device has a device owner.
4035 assertTrue(dpm.isDeviceManaged());
4036 mContext.binder.callingUid = 1234567;
4037 mContext.callerPermissions.add(permission.MANAGE_USERS);
4038 assertTrue(dpm.isDeviceManaged());
4039 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4040 mContext.binder.clearCallingIdentity();
4041 assertTrue(dpm.isDeviceManaged());
4042
4043 clearDeviceOwner();
4044
4045 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4046 // not have a device owner.
4047 mContext.binder.callingUid = 1234567;
4048 mContext.callerPermissions.add(permission.MANAGE_USERS);
4049 assertFalse(dpm.isDeviceManaged());
4050 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4051 mContext.binder.clearCallingIdentity();
4052 assertFalse(dpm.isDeviceManaged());
4053 }
4054
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004055 public void testDeviceOwnerOrganizationName() throws Exception {
4056 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4057 setupDeviceOwner();
4058
4059 dpm.setOrganizationName(admin1, "organization");
4060
4061 // Device owner can retrieve organization managing the device.
4062 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4063
4064 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4065 mContext.binder.callingUid = 1234567;
4066 mContext.callerPermissions.add(permission.MANAGE_USERS);
4067 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4068 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4069
4070 // System can retrieve organization managing the device.
4071 mContext.binder.clearCallingIdentity();
4072 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4073
4074 // Removing the device owner clears the organization managing the device.
4075 clearDeviceOwner();
4076 assertNull(dpm.getDeviceOwnerOrganizationName());
4077 }
4078
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004079 public void testWipeDataManagedProfile() throws Exception {
4080 final int MANAGED_PROFILE_USER_ID = 15;
4081 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4082 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4083 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4084
4085 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004086 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004087 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004088 // Get mock reason string since we throw an IAE with empty string input.
4089 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4090 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004091
4092 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004093 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004094 MANAGED_PROFILE_USER_ID);
4095 }
4096
4097 public void testWipeDataManagedProfileDisallowed() throws Exception {
4098 final int MANAGED_PROFILE_USER_ID = 15;
4099 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4100 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4101
4102 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004103 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004104 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4105
Pavel Grafov75c0a892017-05-18 17:28:27 +01004106 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004107 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4108 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4109 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004110 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4111 thenReturn("Just a test string.");
4112
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004113 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004114 // The PO is not allowed to remove the profile if the user restriction was set on the
4115 // profile by the system
4116 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4117 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004118 }
4119
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004120 public void testWipeDataDeviceOwner() throws Exception {
4121 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004122 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004123 UserManager.DISALLOW_FACTORY_RESET,
4124 UserHandle.SYSTEM))
4125 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004126 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4127 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004128
4129 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004130 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004131 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4132 /*wipeEuicc=*/ eq(false));
4133 }
4134
4135 public void testWipeEuiccDataEnabled() throws Exception {
4136 setDeviceOwner();
4137 when(getServices().userManager.getUserRestrictionSource(
4138 UserManager.DISALLOW_FACTORY_RESET,
4139 UserHandle.SYSTEM))
4140 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004141 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4142 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004143
4144 dpm.wipeData(WIPE_EUICC);
4145 verify(getServices().recoverySystem).rebootWipeUserData(
4146 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4147 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004148 }
4149
4150 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4151 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004152 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004153 UserManager.DISALLOW_FACTORY_RESET,
4154 UserHandle.SYSTEM))
4155 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004156 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4157 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004158 // The DO is not allowed to wipe the device if the user restriction was set
4159 // by the system
4160 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4161 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004162 }
4163
4164 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4165 final int MANAGED_PROFILE_USER_ID = 15;
4166 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4167 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4168
4169 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004170 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004171 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4172
Pavel Grafov75c0a892017-05-18 17:28:27 +01004173 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004174 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4175 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4176 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4177
4178 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4179 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4180
4181 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4182 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4183 // Failed password attempts on the parent user are taken into account, as there isn't a
4184 // separate work challenge.
4185 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4186 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4187 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4188
4189 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4190 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004191 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004192 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004193 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004194 }
4195
4196 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4197 throws Exception {
4198 final int MANAGED_PROFILE_USER_ID = 15;
4199 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4200 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4201
4202 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004203 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004204 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4205
Pavel Grafov75c0a892017-05-18 17:28:27 +01004206 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004207 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4208 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4209 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4210
4211 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4212 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4213
4214 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4215 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4216 // Failed password attempts on the parent user are taken into account, as there isn't a
4217 // separate work challenge.
4218 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4219 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4220 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4221
4222 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4223 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004224 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004225 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004226 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004227 }
4228
4229 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4230 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004231 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004232 UserManager.DISALLOW_FACTORY_RESET,
4233 UserHandle.SYSTEM))
4234 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4235
4236 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4237
4238 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4239 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4240 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4241 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4242 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4243
4244 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4245 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004246 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004247 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4248 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004249 }
4250
4251 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4252 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004253 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004254 UserManager.DISALLOW_FACTORY_RESET,
4255 UserHandle.SYSTEM))
4256 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4257
4258 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4259
4260 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4261 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4262 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4263 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4264 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4265
4266 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004267 verifyZeroInteractions(getServices().recoverySystem);
4268 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004269 .removeUserEvenWhenDisallowed(anyInt());
4270 }
4271
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004272 public void testGetPermissionGrantState() throws Exception {
4273 final String permission = "some.permission";
4274 final String app1 = "com.example.app1";
4275 final String app2 = "com.example.app2";
4276
Pavel Grafov75c0a892017-05-18 17:28:27 +01004277 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004278 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004279 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004280 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004281 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004282 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4283 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004284 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004285 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004286 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004287 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004288 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004289 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4290
4291 // System can retrieve permission grant state.
4292 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004293 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004294 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4295 dpm.getPermissionGrantState(null, app1, permission));
4296 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4297 dpm.getPermissionGrantState(null, app2, permission));
4298
4299 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004300 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4301 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004302 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4303 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004304
4305 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004306 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4307 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004308 setAsProfileOwner(admin1);
4309 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4310 dpm.getPermissionGrantState(admin1, app1, permission));
4311 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4312 dpm.getPermissionGrantState(admin1, app2, permission));
4313 }
4314
Rubin Xuaab7a412016-12-30 21:13:29 +00004315 public void testResetPasswordWithToken() throws Exception {
4316 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4317 setupDeviceOwner();
4318 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004319 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4320 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4321
Rubin Xuaab7a412016-12-30 21:13:29 +00004322 // test adding a token
4323 final byte[] token = new byte[32];
4324 final long handle = 123456;
4325 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004326 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4327 nullable(EscrowTokenStateChangeCallback.class)))
4328 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004329 assertTrue(dpm.setResetPasswordToken(admin1, token));
4330
4331 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004332 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004333 .thenReturn(true);
4334 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4335
4336 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004337 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4338 eq(LockscreenCredential.createPassword(password)),
4339 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004340 eq(UserHandle.USER_SYSTEM)))
4341 .thenReturn(true);
4342 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4343
4344 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004345 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004346 .thenReturn(true);
4347 assertTrue(dpm.clearResetPasswordToken(admin1));
4348 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004349
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004350 public void testIsActivePasswordSufficient() throws Exception {
4351 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4352 mContext.packageName = admin1.getPackageName();
4353 setupDeviceOwner();
4354
4355 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4356 dpm.setPasswordMinimumLength(admin1, 8);
4357 dpm.setPasswordMinimumLetters(admin1, 6);
4358 dpm.setPasswordMinimumLowerCase(admin1, 3);
4359 dpm.setPasswordMinimumUpperCase(admin1, 1);
4360 dpm.setPasswordMinimumNonLetter(admin1, 1);
4361 dpm.setPasswordMinimumNumeric(admin1, 1);
4362 dpm.setPasswordMinimumSymbols(admin1, 0);
4363
Rubin Xucc391c22018-01-02 20:37:35 +00004364 reset(mContext.spiedContext);
4365
Pavel Grafov6f334842019-08-06 14:37:06 +01004366 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004367
4368 setActivePasswordState(passwordMetricsNoSymbols);
4369 assertTrue(dpm.isActivePasswordSufficient());
4370
4371 initializeDpms();
4372 reset(mContext.spiedContext);
4373 assertTrue(dpm.isActivePasswordSufficient());
4374
4375 // This call simulates the user entering the password for the first time after a reboot.
4376 // This causes password metrics to be reloaded into memory. Until this happens,
4377 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4378 // even if the DPC changes password requirements so that the password no longer meets the
4379 // requirements. This is a known limitation of the current implementation of
4380 // isActivePasswordSufficient() - see b/34218769.
4381 setActivePasswordState(passwordMetricsNoSymbols);
4382 assertTrue(dpm.isActivePasswordSufficient());
4383
4384 dpm.setPasswordMinimumSymbols(admin1, 1);
4385 // This assertion would fail if we had not called setActivePasswordState() again after
4386 // initializeDpms() - see previous comment.
4387 assertFalse(dpm.isActivePasswordSufficient());
4388
4389 initializeDpms();
4390 reset(mContext.spiedContext);
4391 assertFalse(dpm.isActivePasswordSufficient());
4392
Pavel Grafov6f334842019-08-06 14:37:06 +01004393 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004394
4395 setActivePasswordState(passwordMetricsWithSymbols);
4396 assertTrue(dpm.isActivePasswordSufficient());
4397 }
4398
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004399 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4400 // If there is no lock screen, the password is considered empty no matter what, because
4401 // it provides no security.
4402 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4403
4404 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4405 mContext.packageName = admin1.getPackageName();
4406 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004407 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4408 // When there is no lockscreen, user password metrics is always empty.
4409 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004410 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004411
4412 // If no password requirements are set, isActivePasswordSufficient should succeed.
4413 assertTrue(dpm.isActivePasswordSufficient());
4414
4415 // Now set some password quality requirements.
4416 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4417
4418 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004419 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004420 dpm.reportPasswordChanged(userHandle);
4421
4422 // No broadcast should be sent.
4423 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4424 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4425 MockUtils.checkUserHandle(userHandle));
4426
4427 // The active (nonexistent) password doesn't comply with the requirements.
4428 assertFalse(dpm.isActivePasswordSufficient());
4429 }
4430
Pavel Grafov75c0a892017-05-18 17:28:27 +01004431 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4432 throws Exception {
4433 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004434 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004435
Rubin Xu19854862019-08-15 16:37:23 +01004436 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4437 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004438 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004439
Rubin Xucc391c22018-01-02 20:37:35 +00004440 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4441 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004442 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004443 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4444 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004445 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004446 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4447 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004448 // userId, if the password checkpoint value changes.
4449 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4450 MockUtils.checkIntentAction(
4451 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4452 MockUtils.checkUserHandle(userHandle));
4453 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004454 MockUtils.checkIntentAction(
4455 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4456 MockUtils.checkUserHandle(userHandle));
4457
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4459 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004460 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461
4462 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4463 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004464 MockUtils.checkUserHandle(userHandle),
4465 eq(null),
4466 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004467
4468 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4469 // let it finish with system uid, otherwise it will throw and crash.
4470 flushTasks();
4471
4472 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004473 }
4474
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004475 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4476 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4477 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4478 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4479 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4480 DpmMockContext.SYSTEM_UID);
4481 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4482 DpmMockContext.SYSTEM_UID);
4483
4484 // Set up a device owner.
4485 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004486 setupDeviceOwner();
4487
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004488 // First and second user set IMEs manually.
4489 mContext.binder.callingUid = firstUserSystemUid;
4490 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4491 mContext.binder.callingUid = secondUserSystemUid;
4492 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004493
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004494 // Device owner changes IME for first user.
4495 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004496 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004497 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004498 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004499 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004500 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004501 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004502 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4503 mContext.binder.callingUid = firstUserSystemUid;
4504 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4505 mContext.binder.callingUid = secondUserSystemUid;
4506 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004507
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004508 // Second user changes IME manually.
4509 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4510 mContext.binder.callingUid = firstUserSystemUid;
4511 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4512 mContext.binder.callingUid = secondUserSystemUid;
4513 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004514
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004515 // First user changes IME manually.
4516 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4517 mContext.binder.callingUid = firstUserSystemUid;
4518 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4519 mContext.binder.callingUid = secondUserSystemUid;
4520 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004521
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004522 // Device owner changes IME for first user again.
4523 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004524 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004525 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004526 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004527 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004528 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004529 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4530 mContext.binder.callingUid = firstUserSystemUid;
4531 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4532 mContext.binder.callingUid = secondUserSystemUid;
4533 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004534
4535 // Restarting the DPMS should not lose information.
4536 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004537 mContext.binder.callingUid = firstUserSystemUid;
4538 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4539 mContext.binder.callingUid = secondUserSystemUid;
4540 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004541
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004542 // Device owner can find out whether it set the current IME itself.
4543 mContext.binder.callingUid = deviceOwnerUid;
4544 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004545
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004546 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004547 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004548 mContext.binder.callingUid = firstUserSystemUid;
4549 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4550 mContext.binder.callingUid = secondUserSystemUid;
4551 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004552 }
4553
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004554 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4555 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4556 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4557 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4558 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4559 DpmMockContext.SYSTEM_UID);
4560 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4561 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004562
4563 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004564 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004565 setupProfileOwner();
4566
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004567 // First and second user set IMEs manually.
4568 mContext.binder.callingUid = firstUserSystemUid;
4569 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4570 mContext.binder.callingUid = secondUserSystemUid;
4571 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004572
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004573 // Profile owner changes IME for second user.
4574 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004575 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004576 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004577 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004578 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004579 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004580 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004581 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4582 mContext.binder.callingUid = firstUserSystemUid;
4583 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4584 mContext.binder.callingUid = secondUserSystemUid;
4585 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004586
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004587 // First user changes IME manually.
4588 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4589 mContext.binder.callingUid = firstUserSystemUid;
4590 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4591 mContext.binder.callingUid = secondUserSystemUid;
4592 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004593
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004594 // Second user changes IME manually.
4595 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4596 mContext.binder.callingUid = firstUserSystemUid;
4597 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4598 mContext.binder.callingUid = secondUserSystemUid;
4599 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004600
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004601 // Profile owner changes IME for second user again.
4602 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004603 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004604 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004605 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004606 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004607 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004608 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4609 mContext.binder.callingUid = firstUserSystemUid;
4610 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4611 mContext.binder.callingUid = secondUserSystemUid;
4612 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004613
4614 // Restarting the DPMS should not lose information.
4615 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004616 mContext.binder.callingUid = firstUserSystemUid;
4617 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4618 mContext.binder.callingUid = secondUserSystemUid;
4619 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004620
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004621 // Profile owner can find out whether it set the current IME itself.
4622 mContext.binder.callingUid = profileOwnerUid;
4623 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004624
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004625 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004626 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004627 mContext.binder.callingUid = firstUserSystemUid;
4628 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4629 mContext.binder.callingUid = secondUserSystemUid;
4630 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004631 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004632
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004633 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4634 throws Exception {
4635 // Set up a device owner.
4636 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4637 setupDeviceOwner();
4638 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4639 }
4640
4641 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4642 throws Exception {
4643 // Set up a profile owner.
4644 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4645 setupProfileOwner();
4646 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4647 }
4648
4649 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4650 int adminUid) throws Exception {
4651 mContext.binder.callingUid = adminUid;
4652 final int userId = UserHandle.getUserId(adminUid);
4653
4654 final String packageName = "some.package";
4655 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4656 admin1, Collections.singletonList(packageName)));
4657 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4658
4659 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4660 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4661
4662 // Attempt to set to empty list (which means no listener is whitelisted)
4663 mContext.binder.callingUid = adminUid;
4664 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004665 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004666 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4667
4668 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4669 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4670 }
4671
4672 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4673 // Set up a managed profile
4674 final int MANAGED_PROFILE_USER_ID = 15;
4675 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4676 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4677 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4678
4679 final String permittedListener = "some.package";
4680 setupPackageInPackageManager(
4681 permittedListener,
4682 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4683 /*appId=*/ 12345, /*flags=*/ 0);
4684
4685 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4686 admin1, Collections.singletonList(permittedListener)));
4687
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004688 // isNotificationListenerServicePermitted should throw if not called from System.
4689 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4690 () -> dpms.isNotificationListenerServicePermitted(
4691 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004692
4693 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4694 assertTrue(dpms.isNotificationListenerServicePermitted(
4695 permittedListener, MANAGED_PROFILE_USER_ID));
4696 }
4697
4698 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4699 throws Exception {
4700 // Set up a managed profile
4701 final int MANAGED_PROFILE_USER_ID = 15;
4702 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4703 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4704 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4705
4706 final String permittedListener = "permitted.package";
4707 int appId = 12345;
4708 setupPackageInPackageManager(
4709 permittedListener,
4710 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4711 appId, /*flags=*/ 0);
4712
4713 final String notPermittedListener = "not.permitted.package";
4714 setupPackageInPackageManager(
4715 notPermittedListener,
4716 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4717 ++appId, /*flags=*/ 0);
4718
4719 final String systemListener = "system.package";
4720 setupPackageInPackageManager(
4721 systemListener,
4722 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4723 ++appId, ApplicationInfo.FLAG_SYSTEM);
4724
4725 // By default all packages are allowed
4726 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4727
4728 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4729 assertTrue(dpms.isNotificationListenerServicePermitted(
4730 permittedListener, MANAGED_PROFILE_USER_ID));
4731 assertTrue(dpms.isNotificationListenerServicePermitted(
4732 notPermittedListener, MANAGED_PROFILE_USER_ID));
4733 assertTrue(dpms.isNotificationListenerServicePermitted(
4734 systemListener, MANAGED_PROFILE_USER_ID));
4735
4736 // Setting only one package in the whitelist
4737 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4738 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4739 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004740 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004741 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4742 assertEquals(1, permittedListeners.size());
4743 assertEquals(permittedListener, permittedListeners.get(0));
4744
4745 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4746 assertTrue(dpms.isNotificationListenerServicePermitted(
4747 permittedListener, MANAGED_PROFILE_USER_ID));
4748 assertFalse(dpms.isNotificationListenerServicePermitted(
4749 notPermittedListener, MANAGED_PROFILE_USER_ID));
4750 // System packages are always allowed (even if not in the whitelist)
4751 assertTrue(dpms.isNotificationListenerServicePermitted(
4752 systemListener, MANAGED_PROFILE_USER_ID));
4753
4754 // Setting an empty whitelist - only system listeners allowed
4755 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4756 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004757 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004758 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4759
4760 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4761 assertFalse(dpms.isNotificationListenerServicePermitted(
4762 permittedListener, MANAGED_PROFILE_USER_ID));
4763 assertFalse(dpms.isNotificationListenerServicePermitted(
4764 notPermittedListener, MANAGED_PROFILE_USER_ID));
4765 // System packages are always allowed (even if not in the whitelist)
4766 assertTrue(dpms.isNotificationListenerServicePermitted(
4767 systemListener, MANAGED_PROFILE_USER_ID));
4768
4769 // Setting a null whitelist - all listeners allowed
4770 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4771 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4772 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4773
4774 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4775 assertTrue(dpms.isNotificationListenerServicePermitted(
4776 permittedListener, MANAGED_PROFILE_USER_ID));
4777 assertTrue(dpms.isNotificationListenerServicePermitted(
4778 notPermittedListener, MANAGED_PROFILE_USER_ID));
4779 assertTrue(dpms.isNotificationListenerServicePermitted(
4780 systemListener, MANAGED_PROFILE_USER_ID));
4781 }
4782
4783 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4784 throws Exception {
4785 // Set up a managed profile
4786 final int MANAGED_PROFILE_USER_ID = 15;
4787 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4788 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4789 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4790
4791 final String nonSystemPackage = "non.system.package";
4792 int appId = 12345;
4793 setupPackageInPackageManager(
4794 nonSystemPackage,
4795 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4796 appId, /*flags=*/ 0);
4797
4798 final String systemListener = "system.package";
4799 setupPackageInPackageManager(
4800 systemListener,
4801 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4802 ++appId, ApplicationInfo.FLAG_SYSTEM);
4803
4804 // By default all packages are allowed (for all profiles)
4805 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4806
4807 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4808 assertTrue(dpms.isNotificationListenerServicePermitted(
4809 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4810 assertTrue(dpms.isNotificationListenerServicePermitted(
4811 systemListener, MANAGED_PROFILE_USER_ID));
4812 assertTrue(dpms.isNotificationListenerServicePermitted(
4813 nonSystemPackage, UserHandle.USER_SYSTEM));
4814 assertTrue(dpms.isNotificationListenerServicePermitted(
4815 systemListener, UserHandle.USER_SYSTEM));
4816
4817 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4818 // all allowed in primary profile
4819 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4820 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004821 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004822 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4823
4824 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4825 assertFalse(dpms.isNotificationListenerServicePermitted(
4826 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4827 assertTrue(dpms.isNotificationListenerServicePermitted(
4828 systemListener, MANAGED_PROFILE_USER_ID));
4829 assertTrue(dpms.isNotificationListenerServicePermitted(
4830 nonSystemPackage, UserHandle.USER_SYSTEM));
4831 assertTrue(dpms.isNotificationListenerServicePermitted(
4832 systemListener, UserHandle.USER_SYSTEM));
4833 }
4834
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004835 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004836 mServiceContext.packageName = mRealTestContext.getPackageName();
4837 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4838 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004839 setDeviceOwner();
4840
Pavel Grafov75c0a892017-05-18 17:28:27 +01004841 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004842 }
4843
4844 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004845 mServiceContext.packageName = mRealTestContext.getPackageName();
4846 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4847 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004848 setAsProfileOwner(admin1);
4849
Pavel Grafov75c0a892017-05-18 17:28:27 +01004850 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4851 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004852 }
4853
4854 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004855 mServiceContext.packageName = mRealTestContext.getPackageName();
4856 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4857 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004858 setAsProfileOwner(admin1);
4859
Pavel Grafov75c0a892017-05-18 17:28:27 +01004860 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4861 caller.packageName = "com.example.delegate";
4862 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4863 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004864
Pavel Grafov75c0a892017-05-18 17:28:27 +01004865 // Make caller a delegated cert installer.
4866 runAsCaller(mAdmin1Context, dpms,
4867 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004868
4869 verifyCanGetOwnerInstalledCaCerts(null, caller);
4870 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004871 }
4872
Rubin Xucc391c22018-01-02 20:37:35 +00004873 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004874 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4875 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004876 Bundle restriction = new Bundle();
4877 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4878
4879 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4880 RestrictionsListener listener = new RestrictionsListener(mContext);
4881 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4882 new Bundle());
4883 verifyDataSharingChangedBroadcast();
4884 }
4885
4886 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004887 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4888 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004889 Bundle restriction = new Bundle();
4890 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4891
4892 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4893 RestrictionsListener listener = new RestrictionsListener(mContext);
4894 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4895 restriction);
4896 verifyDataSharingChangedBroadcast();
4897 }
4898
4899 public void testDisallowSharingIntoProfileUnchanged() {
4900 RestrictionsListener listener = new RestrictionsListener(mContext);
4901 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4902 new Bundle());
4903 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4904 }
4905
4906 private void verifyDataSharingChangedBroadcast() {
4907 Intent expectedIntent = new Intent(
4908 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4909 expectedIntent.setPackage("com.android.managedprovisioning");
4910 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4911 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4912 MockUtils.checkIntent(expectedIntent),
4913 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4914 }
4915
yuemingwe3d9c092018-01-11 12:11:44 +00004916 public void testOverrideApnAPIsFailWithPO() throws Exception {
4917 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004918 ApnSetting apn = (new ApnSetting.Builder())
4919 .setApnName("test")
4920 .setEntryName("test")
4921 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4922 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004923 assertExpectException(SecurityException.class, null, () ->
4924 dpm.addOverrideApn(admin1, apn));
4925 assertExpectException(SecurityException.class, null, () ->
4926 dpm.updateOverrideApn(admin1, 0, apn));
4927 assertExpectException(SecurityException.class, null, () ->
4928 dpm.removeOverrideApn(admin1, 0));
4929 assertExpectException(SecurityException.class, null, () ->
4930 dpm.getOverrideApns(admin1));
4931 assertExpectException(SecurityException.class, null, () ->
4932 dpm.setOverrideApnsEnabled(admin1, false));
4933 assertExpectException(SecurityException.class, null, () ->
4934 dpm.isOverrideApnEnabled(admin1));
4935 }
4936
Robin Lee2c68dad2017-03-17 12:50:24 +00004937 private void verifyCanGetOwnerInstalledCaCerts(
4938 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004939 final String alias = "cert";
4940 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004941
4942 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004943 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004944 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4945 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004946 }
4947 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4948
4949 // caller: device admin or delegated certificate installer
4950 callerContext.applicationInfo = new ApplicationInfo();
4951 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4952
4953 // system_server
4954 final DpmMockContext serviceContext = mContext;
4955 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004956 getServices().addPackageContext(callerUser, admin1Context);
4957 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004958
4959 // Install a CA cert.
4960 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004961 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004962 .thenReturn(alias);
4963 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004964 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004965 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004966 });
4967
Pavel Grafov75c0a892017-05-18 17:28:27 +01004968 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4969 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4970 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004971 flushTasks();
4972
Robin Lee2c68dad2017-03-17 12:50:24 +00004973 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4974
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004975 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004976 runAsCaller(admin1Context, dpms, (dpm) -> {
4977 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004978 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004979 ownerInstalledCaCerts.addAll(installedCaCerts);
4980 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004981
4982 // Restarting the DPMS should not lose information.
4983 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004984 runAsCaller(admin1Context, dpms, (dpm) ->
4985 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004986
4987 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004988 runAsCaller(serviceContext, dpms, (dpm) -> {
4989 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004990
Robin Lee2c68dad2017-03-17 12:50:24 +00004991 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004992 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004993 });
4994
Pavel Grafov75c0a892017-05-18 17:28:27 +01004995 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4996 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4997 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004998 flushTasks();
4999
5000 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
5001 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005002 runAsCaller(admin1Context, dpms, (dpm) -> {
5003 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
5004 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005005 }
5006
Robin Lee2c68dad2017-03-17 12:50:24 +00005007 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
5008 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005009 final String alias = "cert";
5010 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005011
5012 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005013 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005014 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5015 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005016 }
5017 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5018
5019 // caller: device admin or delegated certificate installer
5020 callerContext.applicationInfo = new ApplicationInfo();
5021 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5022
5023 // system_server
5024 final DpmMockContext serviceContext = mContext;
5025 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005026 getServices().addPackageContext(callerUser, admin1Context);
5027 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005028
5029 // Install a CA cert as caller
5030 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005031 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005032 .thenReturn(alias);
5033 assertTrue(dpm.installCaCert(callerName, caCert));
5034 });
5035
5036 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005037 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005038 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005039 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5040 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5041 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005042 flushTasks();
5043
Robin Lee2c68dad2017-03-17 12:50:24 +00005044 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005045 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005046
5047 runAsCaller(serviceContext, dpms, (dpm) -> {
5048 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5049 assertNotNull(ownerInstalledCaCerts);
5050 assertTrue(ownerInstalledCaCerts.isEmpty());
5051 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005052 }
5053
Eran Messeri94d56762017-12-21 20:50:54 +00005054 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5055 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5056 Arrays.sort(gotFlags);
5057 Arrays.sort(expectedFlags);
5058 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5059 }
5060
5061 public void testTranslationOfIdAttestationFlag() {
5062 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5063 int[] correspondingAttUtilsTypes = new int[]{
5064 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5065 AttestationUtils.ID_TYPE_MEID};
5066
5067 // Test translation of zero flags
5068 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5069
5070 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5071 // non-null array
5072 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5073
5074 // Test translation of a single flag
5075 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5076 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5077 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5078
5079 // Test translation of two flags
5080 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5081 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5082 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5083 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5084
5085 // Test translation of all three flags
5086 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5087 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5088 AttestationUtils.ID_TYPE_MEID});
5089 // Test translation of all three flags
5090 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5091 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5092 AttestationUtils.ID_TYPE_MEID});
5093 }
5094
arangelov08d534b2018-01-22 15:20:53 +00005095 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5096 setDeviceOwner();
5097 initializeDpms();
5098 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5099 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5100 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5101 }
5102
5103 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5104 DpmTestUtils.writeInputStreamToFile(
5105 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5106 getDeviceOwnerPoliciesFile());
5107 DpmTestUtils.writeInputStreamToFile(
5108 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5109 getDeviceOwnerFile());
5110 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5111 }
5112
5113 public void testRevertDeviceOwnership_deviceNotMigrated()
5114 throws Exception {
5115 DpmTestUtils.writeInputStreamToFile(
5116 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5117 getDeviceOwnerPoliciesFile());
5118 DpmTestUtils.writeInputStreamToFile(
5119 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5120 getDeviceOwnerFile());
5121 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5122 }
5123
5124 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5125 throws Exception {
5126 DpmTestUtils.writeInputStreamToFile(
5127 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5128 getDeviceOwnerPoliciesFile());
5129 DpmTestUtils.writeInputStreamToFile(
5130 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5131 getDeviceOwnerFile());
5132 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5133 }
5134
5135 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5136 setupProfileOwner();
5137 initializeDpms();
5138 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5139 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5140 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5141 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5142 }
5143
5144 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5145 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5146 UserHandle.USER_SYSTEM);
5147 DpmTestUtils.writeInputStreamToFile(
5148 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5149 getProfileOwnerPoliciesFile());
5150 DpmTestUtils.writeInputStreamToFile(
5151 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5152 getProfileOwnerFile());
5153 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5154 }
5155
5156 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5157 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5158 UserHandle.USER_SYSTEM);
5159 DpmTestUtils.writeInputStreamToFile(
5160 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5161 getProfileOwnerPoliciesFile());
5162 DpmTestUtils.writeInputStreamToFile(
5163 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5164 getProfileOwnerFile());
5165 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5166 }
5167
5168 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5169 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5170 UserHandle.USER_SYSTEM);
5171 DpmTestUtils.writeInputStreamToFile(
5172 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5173 getProfileOwnerPoliciesFile());
5174 DpmTestUtils.writeInputStreamToFile(
5175 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5176 getProfileOwnerFile());
5177 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5178 }
5179
Eran Messeribb271892018-10-17 18:27:50 +01005180 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5181 setupProfileOwner();
5182 configureContextForAccess(mContext, false);
5183
5184 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005185 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005186 }
5187
5188 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5189 setupProfileOwner();
5190 configureContextForAccess(mContext, false);
5191
5192 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005193 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005194 }
5195
5196 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5197 setupProfileOwner();
5198
5199 // This method will throw if the system context could not call
Eran Messeri18d21312019-11-14 22:44:40 +00005200 // markProfileOwnerOfOrganizationOwnedDevice successfully.
5201 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005202 }
5203
Eran Messerib8c46e02019-11-07 12:06:18 +00005204 private void configureContextForAccess(DpmMockContext context, boolean granted) {
Eran Messeribb271892018-10-17 18:27:50 +01005205 when(context.spiedContext.checkCallingPermission(
Eran Messeri18d21312019-11-14 22:44:40 +00005206 permission.MARK_DEVICE_ORGANIZATION_OWNED))
Eran Messeribb271892018-10-17 18:27:50 +01005207 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5208 : PackageManager.PERMISSION_DENIED);
Eran Messerib8c46e02019-11-07 12:06:18 +00005209
5210 when(getServices().userManager.getProfileParent(any()))
5211 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005212 }
5213
5214 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5215 setupProfileOwner();
5216
5217 final long ident = mServiceContext.binder.clearCallingIdentity();
5218 configureContextForAccess(mServiceContext, true);
5219
5220 mServiceContext.binder.callingUid =
5221 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5222 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5223 try {
5224 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005225 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005226 });
5227 } finally {
5228 mServiceContext.binder.restoreCallingIdentity(ident);
5229 }
5230 }
5231
5232 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5233 throws Exception {
5234 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5235 setupDeviceOwner();
5236 configureContextForAccess(mContext, false);
5237
5238 // Device owner should be allowed to request Device ID attestation.
5239 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5240 DpmMockContext.CALLER_SYSTEM_USER_UID);
5241
5242 // Another package must not be allowed to request Device ID attestation.
5243 assertExpectException(SecurityException.class, null,
5244 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5245 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5246 // Another component that is not the admin must not be allowed to request Device ID
5247 // attestation.
5248 assertExpectException(SecurityException.class, null,
5249 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5250 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5251 }
5252
5253 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5254 throws Exception {
5255 configureContextForAccess(mContext, false);
5256
5257 // Make sure a security exception is thrown if the device has no profile owner.
5258 assertExpectException(SecurityException.class, null,
5259 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5260 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5261
5262 setupProfileOwner();
Eran Messeri18d21312019-11-14 22:44:40 +00005263 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005264
5265 // The profile owner is allowed to request Device ID attestation.
5266 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5267 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5268 DpmMockContext.CALLER_UID);
5269 // But not another package.
5270 assertExpectException(SecurityException.class, null,
5271 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5272 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5273 // Or another component which is not the admin.
5274 assertExpectException(SecurityException.class, null,
5275 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5276 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5277 }
5278
5279 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5280 final long ident = mServiceContext.binder.clearCallingIdentity();
5281
5282 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5283 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5284 try {
5285 runAsCaller(mServiceContext, dpms, action);
5286 } finally {
5287 mServiceContext.binder.restoreCallingIdentity(ident);
5288 }
5289 }
5290
5291 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5292 setupProfileOwner();
5293 markDelegatedCertInstallerAsInstalled();
5294
5295 // Configure a delegated cert installer.
5296 runAsCaller(mServiceContext, dpms,
5297 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5298 Arrays.asList(DELEGATION_CERT_INSTALL)));
5299
Eran Messeri18d21312019-11-14 22:44:40 +00005300 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005301
5302 // Make sure that the profile owner can still request Device ID attestation.
5303 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5304 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5305 DpmMockContext.CALLER_UID);
5306
5307 runAsDelegatedCertInstaller(dpm -> {
5308 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5309 DpmMockContext.DELEGATE_PACKAGE_NAME,
5310 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5311 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5312 });
5313 }
5314
5315 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5316 throws Exception {
5317 setupProfileOwner();
5318 markDelegatedCertInstallerAsInstalled();
5319
5320 // Configure a delegated cert installer.
5321 runAsCaller(mServiceContext, dpms,
5322 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5323 Arrays.asList(DELEGATION_CERT_INSTALL)));
5324
5325
5326 assertExpectException(SecurityException.class, null,
5327 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5328 admin1.getPackageName(),
5329 DpmMockContext.CALLER_UID));
5330
5331 runAsDelegatedCertInstaller(dpm -> {
5332 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5333 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5334 DpmMockContext.DELEGATE_PACKAGE_NAME,
5335 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5336 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5337 });
5338 }
5339
Alex Johnston07cb9f02019-11-01 17:40:38 +00005340 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
5341 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5342 setAsProfileOwner(admin1);
5343
5344 new DevicePolicyManagerTestable(
5345 mServiceContext,
5346 dpms,
5347 /* parentInstance= */ true)
5348 .getPasswordComplexity();
5349
5350 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005351 }
5352
5353 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5354 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5355 .thenReturn(false);
5356 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5357 }
5358
5359 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5360 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5361 .thenReturn(true);
5362 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5363 }
5364
5365
5366 public void testGetPasswordComplexity_currentUserNoPassword() {
5367 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5368 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005369 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005370 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5371 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5372
5373 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5374 }
5375
5376 public void testGetPasswordComplexity_currentUserHasPassword() {
5377 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5378 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005379 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005380 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5381 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005382 when(getServices().lockSettingsInternal
5383 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005384 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005385
5386 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5387 }
5388
5389 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5390 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5391 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005392 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005393
5394 UserInfo parentUser = new UserInfo();
5395 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5396 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5397 .thenReturn(parentUser.id);
5398
Rubin Xu19854862019-08-15 16:37:23 +01005399 when(getServices().lockSettingsInternal
5400 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005401 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005402 when(getServices().lockSettingsInternal
5403 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005404 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005405
5406 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5407 }
5408
yuemingwd2bfbc82019-01-02 11:42:25 +00005409 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5410 setAsProfileOwner(admin1);
5411 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5412 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5413 }
5414
5415 public void testCrossProfileCalendarPackages_reopenDpms() {
5416 setAsProfileOwner(admin1);
5417 dpm.setCrossProfileCalendarPackages(admin1, null);
5418 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5419 assertTrue(packages == null);
5420 initializeDpms();
5421 packages = dpm.getCrossProfileCalendarPackages(admin1);
5422 assertTrue(packages == null);
5423
5424 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5425 packages = dpm.getCrossProfileCalendarPackages(admin1);
5426 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5427 initializeDpms();
5428 packages = dpm.getCrossProfileCalendarPackages(admin1);
5429 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5430
5431 final String dummyPackageName = "test";
5432 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5433 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5434 packages = dpm.getCrossProfileCalendarPackages(admin1);
5435 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5436 initializeDpms();
5437 packages = dpm.getCrossProfileCalendarPackages(admin1);
5438 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5439 }
5440
5441 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5442 assertTrue(expected != null);
5443 assertTrue(actual != null);
5444 assertTrue(expected.containsAll(actual));
5445 assertTrue(actual.containsAll(expected));
5446 }
5447
yuemingwdded98f2019-01-30 17:08:12 +00005448 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5449 setAsProfileOwner(admin1);
5450 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5451 when(getServices().settings.settingsSecureGetIntForUser(
5452 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5453 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5454 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5455 }
5456
5457 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5458 final String testPackage = "TEST_PACKAGE";
5459 setAsProfileOwner(admin1);
5460 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5461 when(getServices().settings.settingsSecureGetIntForUser(
5462 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5463 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5464 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5465 }
5466
5467 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5468 final String testPackage = "TEST_PACKAGE";
5469 setAsProfileOwner(admin1);
5470 dpm.setCrossProfileCalendarPackages(admin1, null);
5471 when(getServices().settings.settingsSecureGetIntForUser(
5472 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5473 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5474 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5475 }
5476
Eran Messeri18d21312019-11-14 22:44:40 +00005477 private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
Eran Messerib8c46e02019-11-07 12:06:18 +00005478 when(getServices().userManager.getProfileParent(eq(UserHandle.of(userId))))
5479 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005480 final long ident = mServiceContext.binder.clearCallingIdentity();
5481 mServiceContext.binder.callingUid =
5482 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
Eran Messeri18d21312019-11-14 22:44:40 +00005483
5484 configureContextForAccess(mServiceContext, true);
Eran Messeribb271892018-10-17 18:27:50 +01005485 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005486 dpm.markProfileOwnerOnOrganizationOwnedDevice(who);
Eran Messeribb271892018-10-17 18:27:50 +01005487 });
5488 mServiceContext.binder.restoreCallingIdentity(ident);
5489 }
5490
arangelov08d534b2018-01-22 15:20:53 +00005491 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5492 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5493 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5494 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5495
5496 final long ident = mServiceContext.binder.clearCallingIdentity();
5497 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5498 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5499 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5500 // To simulate a reboot, we just reinitialize dpms and call systemReady
5501 initializeDpms();
5502
5503 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5504 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5505 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5506 assertTrue(dpm.isAdminActive(admin1));
5507 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5508 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5509
5510 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5511 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5512 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5513 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5514
5515 mServiceContext.binder.restoreCallingIdentity(ident);
5516 }
5517
5518 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5519 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5520 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5521 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5522
5523 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5524 DpmMockContext.CALLER_SYSTEM_USER_UID);
5525 setUpPackageManagerForAdmin(admin1, uid);
5526 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5527 // To simulate a reboot, we just reinitialize dpms and call systemReady
5528 initializeDpms();
5529
5530 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5531 assertTrue(dpm.isAdminActive(admin1));
5532 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5533 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5534 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5535 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5536 }
5537
5538 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5539 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5540 metadataManager.deleteMetadataFile();
5541
5542 final TransferOwnershipMetadataManager.Metadata metadata =
5543 new TransferOwnershipMetadataManager.Metadata(
5544 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5545 callerUserHandle,
5546 adminType);
5547 metadataManager.saveMetadataFile(metadata);
5548 }
5549
5550 private File getDeviceOwnerFile() {
5551 return dpms.mOwners.getDeviceOwnerFile();
5552 }
5553
5554 private File getProfileOwnerFile() {
5555 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5556 }
5557
5558 private File getProfileOwnerPoliciesFile() {
5559 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5560 DpmMockContext.CALLER_USER_HANDLE);
5561 return getPoliciesFile(parentDir);
5562 }
5563
5564 private File getDeviceOwnerPoliciesFile() {
5565 return getPoliciesFile(getServices().systemUserDataDir);
5566 }
5567
5568 private File getPoliciesFile(File parentDir) {
5569 return new File(parentDir, "device_policies.xml");
5570 }
5571
5572 private InputStream getRawStream(@RawRes int id) {
5573 return mRealTestContext.getResources().openRawResource(id);
5574 }
5575
Victor Chang3e794af2016-03-04 13:48:17 +00005576 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005577 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005578 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5579 dpms.notifyChangeToContentObserver(
5580 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5581 }
5582
5583 private void assertProvisioningAllowed(String action, boolean expected) {
5584 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5585 dpm.isProvisioningAllowed(action));
5586 }
Tony Mak2f26b792016-11-28 17:54:51 +00005587
Nicolas Prevot45d29072017-01-18 16:11:19 +00005588 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5589 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005590 final String previousPackageName = mContext.packageName;
5591 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005592
5593 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5594 mContext.packageName = packageName;
5595 mMockContext.binder.callingUid = uid;
5596 assertProvisioningAllowed(action, expected);
5597
5598 // Set the previous package name / calling uid to go back to the initial state.
5599 mContext.packageName = previousPackageName;
5600 mMockContext.binder.callingUid = previousUid;
5601 }
5602
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005603 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005604 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5605 }
5606
5607 private void assertCheckProvisioningPreCondition(
5608 String action, String packageName, int provisioningCondition) {
5609 assertEquals("checkProvisioningPreCondition("
5610 + action + ", " + packageName + ") returning unexpected result",
5611 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005612 }
5613
Tony Mak2f26b792016-11-28 17:54:51 +00005614 /**
5615 * Setup a managed profile with the specified admin and its uid.
5616 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5617 * @param adminUid uid of the admin package.
5618 * @param copyFromAdmin package information for {@code admin} will be built based on this
5619 * component's information.
5620 */
5621 private void addManagedProfile(
5622 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5623 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005624 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005625 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5626 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5627 dpm.setActiveAdmin(admin, false, userId);
5628 assertTrue(dpm.setProfileOwner(admin, null, userId));
5629 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5630 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005631
5632 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005633 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005634 */
Robin Leeabaa0692017-02-20 20:54:22 +00005635 private static StringParceledListSlice asSlice(String[] s) {
5636 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005637 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005638
5639 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005640 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5641 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005642
Robin Lee2c68dad2017-03-17 12:50:24 +00005643 // We can't let exceptions happen on the background thread. Throw them here if they happen
5644 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005645 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005646 }
Victor Chang3e794af2016-03-04 13:48:17 +00005647}