blob: 09d1d3a270bace6418a9b6d537bb3cecab83e44a [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 Grafov4513e242020-01-31 11:41:51 +000029import static android.content.pm.ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE;
Pavel Grafov6a40f092016-10-25 15:46:51 +010030
Pavel Grafov6f334842019-08-06 14:37:06 +010031import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Alex Johnston011f5c62019-12-18 17:05:57 +000035import static com.google.common.truth.Truth.assertThat;
36
Pavel Grafov75c0a892017-05-18 17:28:27 +010037import static org.mockito.Matchers.any;
Eran Messeri6ad0e192019-12-01 20:01:21 +000038import static org.mockito.Matchers.anyBoolean;
Pavel Grafov75c0a892017-05-18 17:28:27 +010039import static org.mockito.Matchers.anyInt;
40import static org.mockito.Matchers.anyLong;
41import static org.mockito.Matchers.anyObject;
42import static org.mockito.Matchers.anyString;
43import static org.mockito.Matchers.eq;
44import static org.mockito.Matchers.isNull;
45import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010046import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010047import static org.mockito.Mockito.doAnswer;
48import static org.mockito.Mockito.doReturn;
49import static org.mockito.Mockito.never;
50import static org.mockito.Mockito.nullable;
51import static org.mockito.Mockito.reset;
52import static org.mockito.Mockito.timeout;
53import static org.mockito.Mockito.times;
54import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080055import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056import static org.mockito.Mockito.verifyZeroInteractions;
57import static org.mockito.Mockito.when;
58import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000059import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010060
Makoto Onukif76b06a2015-09-22 15:03:44 -070061import android.Manifest.permission;
62import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010063import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000064import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.app.admin.DeviceAdminReceiver;
66import android.app.admin.DevicePolicyManager;
67import android.app.admin.DevicePolicyManagerInternal;
Alex Johnston011f5c62019-12-18 17:05:57 +000068import android.app.admin.FactoryResetProtectionPolicy;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010069import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000072import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000073import android.content.pm.ApplicationInfo;
74import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010076import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000077import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000078import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010079import android.graphics.Color;
80import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080081import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070082import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080083import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070085import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010086import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080087import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010088import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000089import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000090import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000091import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080092import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010093import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095
Pavel Grafov57f1b662019-03-27 14:55:38 +000096import androidx.test.filters.SmallTest;
97
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010098import com.android.internal.R;
Rubin Xua58125d2019-09-06 20:11:48 +010099import com.android.internal.widget.LockscreenCredential;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100import com.android.server.LocalServices;
101import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +0000102import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Alan Treadwayafad8782016-01-19 15:15:08 +0000103
Robin Lee7f5c91c2017-02-08 21:27:02 +0000104import org.hamcrest.BaseMatcher;
105import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800106import org.mockito.Mockito;
kholoud mohamedfff05762019-12-10 11:38:04 +0000107import org.mockito.internal.util.collections.Sets;
Makoto Onukib643fb02015-09-22 15:03:44 -0700108import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109
arangelov08d534b2018-01-22 15:20:53 +0000110import java.io.File;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800111import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000112import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000113import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700114import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700115import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700116import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100117import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000118import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700121 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000122 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 m FrameworksServicesTests &&
124 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000125 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700127 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700128
129 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000130 *
131 * , or:
132 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000134@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100135@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700136public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000137 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
138 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
139 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100140 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800141 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Eran Messeri6ba10db2019-12-04 15:53:27 +0000142 public static final String NOT_ORG_OWNED_PROFILE_OWNER_MSG =
143 "not the profile owner on organization-owned device";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100144 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000145
Pavel Grafov75c0a892017-05-18 17:28:27 +0100146 // TODO replace all instances of this with explicit {@link #mServiceContext}.
147 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700148 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100149
150 private DpmMockContext mServiceContext;
151 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700152 public DevicePolicyManager dpm;
Alex Johnston755e3772019-11-29 03:27:22 +0000153 public DevicePolicyManager parentDpm;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700154 public DevicePolicyManagerServiceTestable dpms;
155
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100156 /*
157 * The CA cert below is the content of cacert.pem as generated by:
158 *
159 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
160 */
161 private static final String TEST_CA =
162 "-----BEGIN CERTIFICATE-----\n" +
163 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
164 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
165 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
166 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
167 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
168 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
169 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
170 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
171 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
172 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
173 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
174 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
175 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
176 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
177 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
178 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
179 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
180 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
181 "wQ==\n" +
182 "-----END CERTIFICATE-----\n";
183
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700184 @Override
185 protected void setUp() throws Exception {
186 super.setUp();
187
188 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100189 mServiceContext = mContext;
190 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
191 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700192 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100193 doReturn(Collections.singletonList(new ResolveInfo()))
194 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
195 any(Intent.class),
196 anyInt(),
197 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700198
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800199 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100200 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800201
Makoto Onukia52562c2015-10-01 16:12:31 -0700202 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700203
Sudheer Shanka101c3532018-01-08 16:28:42 -0800204 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800205 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700206 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
207 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
208 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800209 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700210
Pavel Grafov75c0a892017-05-18 17:28:27 +0100211 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
212 mAdmin1Context.packageName = admin1.getPackageName();
213 mAdmin1Context.applicationInfo = new ApplicationInfo();
214 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
215
Makoto Onukib643fb02015-09-22 15:03:44 -0700216 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100217
218 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700219 }
220
arangelov08d534b2018-01-22 15:20:53 +0000221 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
222 return dpms.mTransferOwnershipMetadataManager;
223 }
224
Robin Lee2c68dad2017-03-17 12:50:24 +0000225 @Override
226 protected void tearDown() throws Exception {
227 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000228 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000229 super.tearDown();
230 }
231
Makoto Onukia52562c2015-10-01 16:12:31 -0700232 private void initializeDpms() {
233 // Need clearCallingIdentity() to pass permission checks.
234 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236
Pavel Grafov75c0a892017-05-18 17:28:27 +0100237 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
238 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
239 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700240
Pavel Grafov75c0a892017-05-18 17:28:27 +0100241 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700242
Alex Johnston755e3772019-11-29 03:27:22 +0000243 parentDpm = new DevicePolicyManagerTestable(mServiceContext, dpms,
244 /* parentInstance= */true);
245
Pavel Grafov75c0a892017-05-18 17:28:27 +0100246 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700247 }
248
Makoto Onukib643fb02015-09-22 15:03:44 -0700249 private void setUpUserManager() {
250 // Emulate UserManager.set/getApplicationRestriction().
251 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
252
253 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000254 doAnswer((Answer<Void>) invocation -> {
255 String pkg = (String) invocation.getArguments()[0];
256 Bundle bundle = (Bundle) invocation.getArguments()[1];
257 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700258
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000259 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700260
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000261 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100263 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700264
265 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000266 doAnswer((Answer<Bundle>) invocation -> {
267 String pkg = (String) invocation.getArguments()[0];
268 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700269
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000270 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700272 anyString(), any(UserHandle.class));
273
Eran Messeri6ad0e192019-12-01 20:01:21 +0000274 // Emulate UserManager.setUserRestriction/getUserRestrictions
275 final Map<UserHandle, Bundle> userRestrictions = new HashMap<>();
276
277 doAnswer((Answer<Void>) invocation -> {
278 String key = (String) invocation.getArguments()[0];
279 boolean value = (Boolean) invocation.getArguments()[1];
280 UserHandle user = (UserHandle) invocation.getArguments()[2];
281 Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
282 userBundle.putBoolean(key, value);
283
284 userRestrictions.put(user, userBundle);
285 return null;
286 }).when(getServices().userManager).setUserRestriction(
287 anyString(), anyBoolean(), any(UserHandle.class));
288
289 doAnswer((Answer<Boolean>) invocation -> {
290 String key = (String) invocation.getArguments()[0];
291 UserHandle user = (UserHandle) invocation.getArguments()[1];
292 Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
293 return userBundle.getBoolean(key);
294 }).when(getServices().userManager).hasUserRestriction(
295 anyString(), any(UserHandle.class));
296
Makoto Onukid932f762015-09-29 16:53:38 -0700297 // Add the first secondary user.
Alex Johnston755e3772019-11-29 03:27:22 +0000298 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
299 UserManager.USER_TYPE_FULL_SECONDARY);
Makoto Onukib643fb02015-09-22 15:03:44 -0700300 }
301
302 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100303 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700304
Pavel Grafov75c0a892017-05-18 17:28:27 +0100305 mServiceContext.binder.callingUid =
306 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
307 runAsCaller(mServiceContext, dpms, dpm -> {
308 // PO needs to be a DA.
309 dpm.setActiveAdmin(admin, /*replace=*/ false);
310 // Fire!
311 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
312 // Check
313 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
314 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700315
Pavel Grafov75c0a892017-05-18 17:28:27 +0100316 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700317 }
318
319 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100320 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700321 .thenReturn(false);
322
323 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100324 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700325
326 // If the device has no DPMS feature, it shouldn't register the local service.
327 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
328 }
329
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800330 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800331 // Device owner in SYSTEM_USER
332 setDeviceOwner();
333 // Profile owner in CALLER_USER_HANDLE
334 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
335 setAsProfileOwner(admin2);
336 // Active admin in CALLER_USER_HANDLE
337 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
338 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
339 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
340 DpmMockContext.CALLER_USER_HANDLE);
341 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
342 DpmMockContext.CALLER_USER_HANDLE));
343
344 initializeDpms();
345
346 // Verify
347 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800348 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800349 eq(UserHandle.USER_SYSTEM));
350 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800351 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800352 adminAnotherPackage.getPackageName()),
353 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800354 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
355 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
356 }
357
358 public void testLoadAdminData_noAdmins() throws Exception {
359 final int ANOTHER_USER_ID = 15;
Alex Johnston755e3772019-11-29 03:27:22 +0000360 getServices().addUser(ANOTHER_USER_ID, 0, "");
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800361
362 initializeDpms();
363
364 // Verify
365 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
366 null, DpmMockContext.CALLER_USER_HANDLE);
367 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
368 null, ANOTHER_USER_ID);
369 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
370 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800371 }
372
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373 /**
374 * Caller doesn't have proper permissions.
375 */
376 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700377 // 1. Failure cases.
378
379 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100380 assertExpectException(SecurityException.class, /* messageRegex= */ null,
381 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700382
383 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
384 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100385
386 assertExpectException(SecurityException.class, /* messageRegex= */ null,
387 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700388 }
389
Makoto Onukif76b06a2015-09-22 15:03:44 -0700390 /**
391 * Test for:
392 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800393 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700394 * {@link DevicePolicyManager#isAdminActive}
395 * {@link DevicePolicyManager#isAdminActiveAsUser}
396 * {@link DevicePolicyManager#getActiveAdmins}
397 * {@link DevicePolicyManager#getActiveAdminsAsUser}
398 */
399 public void testSetActiveAdmin() throws Exception {
400 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700401 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
402
Makoto Onukif76b06a2015-09-22 15:03:44 -0700403 // 2. Call the API.
404 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700405
406 // 3. Verify internal calls.
407
408 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700409 verify(mContext.spiedContext).sendBroadcastAsUser(
410 MockUtils.checkIntentAction(
411 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
412 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
413 verify(mContext.spiedContext).sendBroadcastAsUser(
414 MockUtils.checkIntentAction(
415 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100416 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
417 eq(null),
418 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700419
Pavel Grafov75c0a892017-05-18 17:28:27 +0100420 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700421 eq(admin1.getPackageName()),
422 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
423 eq(PackageManager.DONT_KILL_APP),
424 eq(DpmMockContext.CALLER_USER_HANDLE),
425 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700426
Sudheer Shanka101c3532018-01-08 16:28:42 -0800427 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
428 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
429
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700430 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431
432 // Make sure it's active admin1.
433 assertTrue(dpm.isAdminActive(admin1));
434 assertFalse(dpm.isAdminActive(admin2));
435 assertFalse(dpm.isAdminActive(admin3));
436
437 // But not admin1 for a different user.
438
439 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
440 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
441 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
442
443 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
444 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
445
446 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
447
448 // Next, add one more admin.
449 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700450 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700451 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700452
453 dpm.setActiveAdmin(admin2, /* replace =*/ false);
454
455 // Now we have two admins.
456 assertTrue(dpm.isAdminActive(admin1));
457 assertTrue(dpm.isAdminActive(admin2));
458 assertFalse(dpm.isAdminActive(admin3));
459
460 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
461 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100462 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700463 eq(admin1.getPackageName()),
464 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
465 eq(PackageManager.DONT_KILL_APP),
466 eq(DpmMockContext.CALLER_USER_HANDLE),
467 anyString());
468
Sudheer Shanka101c3532018-01-08 16:28:42 -0800469 // times(2) because it was previously called for admin1 which is in the same package
470 // as admin2.
471 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
472 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
473
Makoto Onukif76b06a2015-09-22 15:03:44 -0700474 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100475 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
476 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700477
478 // 5. Add the same admin1 again with replace, which should succeed.
479 dpm.setActiveAdmin(admin1, /* replace =*/ true);
480
481 // TODO make sure it's replaced.
482
483 // 6. Test getActiveAdmins()
484 List<ComponentName> admins = dpm.getActiveAdmins();
485 assertEquals(2, admins.size());
486 assertEquals(admin1, admins.get(0));
487 assertEquals(admin2, admins.get(1));
488
Sudheer Shanka101c3532018-01-08 16:28:42 -0800489 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
490 // replaced
491 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
492
Makoto Onukif76b06a2015-09-22 15:03:44 -0700493 // Another user has no admins.
494 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
495
496 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
497 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
498
499 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
500 }
501
Makoto Onukid932f762015-09-29 16:53:38 -0700502 public void testSetActiveAdmin_multiUsers() throws Exception {
503
504 final int ANOTHER_USER_ID = 100;
505 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
506
Alex Johnston755e3772019-11-29 03:27:22 +0000507 getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700508
509 // Set up pacakge manager for the other user.
510 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700511
512 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
513
514 dpm.setActiveAdmin(admin1, /* replace =*/ false);
515
516 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
517 dpm.setActiveAdmin(admin2, /* replace =*/ false);
518
519
520 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
521 assertTrue(dpm.isAdminActive(admin1));
522 assertFalse(dpm.isAdminActive(admin2));
523
524 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
525 assertFalse(dpm.isAdminActive(admin1));
526 assertTrue(dpm.isAdminActive(admin2));
527 }
528
Makoto Onukif76b06a2015-09-22 15:03:44 -0700529 /**
530 * Test for:
531 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800532 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533 */
534 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
535 // 1. Make sure the caller has proper permissions.
536 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
537
538 dpm.setActiveAdmin(admin1, /* replace =*/ false);
539 assertTrue(dpm.isAdminActive(admin1));
540
541 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100542 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
543 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700544 }
545
546 /**
547 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800548 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
549 * BIND_DEVICE_ADMIN.
550 */
551 public void testSetActiveAdmin_permissionCheck() throws Exception {
552 // 1. Make sure the caller has proper permissions.
553 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
554
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100555 assertExpectException(IllegalArgumentException.class,
556 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
557 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800558 assertFalse(dpm.isAdminActive(adminNoPerm));
559
560 // Change the target API level to MNC. Now it can be set as DA.
561 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
562 VERSION_CODES.M);
563 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
564 assertTrue(dpm.isAdminActive(adminNoPerm));
565
566 // TODO Test the "load from the file" case where DA will still be loaded even without
567 // BIND_DEVICE_ADMIN and target API is N.
568 }
569
570 /**
571 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700572 * {@link DevicePolicyManager#removeActiveAdmin}
573 */
574 public void testRemoveActiveAdmin_SecurityException() {
575 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
576
577 // Add admin.
578
579 dpm.setActiveAdmin(admin1, /* replace =*/ false);
580
581 assertTrue(dpm.isAdminActive(admin1));
582
583 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
584
585 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100586 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
587 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700588
589 // Try to remove active admin with a different caller userid should fail too, without
590 // having MANAGE_DEVICE_ADMINS.
591 mContext.callerPermissions.clear();
592
Makoto Onukid932f762015-09-29 16:53:38 -0700593 // Change the caller, and call into DPMS directly with a different user-id.
594
Makoto Onukif76b06a2015-09-22 15:03:44 -0700595 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100596 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
597 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700598 }
599
600 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800601 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
602 * (because we can't send the remove broadcast).
603 */
604 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
605 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
606
607 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
608
609 // Add admin.
610
611 dpm.setActiveAdmin(admin1, /* replace =*/ false);
612
613 assertTrue(dpm.isAdminActive(admin1));
614
615 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
616
617 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100618 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800619 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100620 assertExpectException(IllegalStateException.class,
621 /* messageRegex= */ "User must be running and unlocked",
622 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800623
624 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800625 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
626 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800627
628 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100629 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800630 .thenReturn(true);
631
632 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700633 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800634 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
635 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800636 }
637
638 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700639 * Test for:
640 * {@link DevicePolicyManager#removeActiveAdmin}
641 */
Makoto Onukid932f762015-09-29 16:53:38 -0700642 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700643 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
644
645 // Add admin1.
646
647 dpm.setActiveAdmin(admin1, /* replace =*/ false);
648
649 assertTrue(dpm.isAdminActive(admin1));
650 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
651
652 // Different user, but should work, because caller has proper permissions.
653 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700654
655 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700656 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700657
658 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700659 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800660 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
661 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700662
663 // TODO DO Still can't be removed in this case.
664 }
665
666 /**
667 * Test for:
668 * {@link DevicePolicyManager#removeActiveAdmin}
669 */
670 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
671 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
672 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
673
674 // Add admin1.
675
676 dpm.setActiveAdmin(admin1, /* replace =*/ false);
677
678 assertTrue(dpm.isAdminActive(admin1));
679 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
680
681 // Broadcast from saveSettingsLocked().
682 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
683 MockUtils.checkIntentAction(
684 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
685 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
686
687 // Remove. No permissions, but same user, so it'll work.
688 mContext.callerPermissions.clear();
689 dpm.removeActiveAdmin(admin1);
690
Makoto Onukif76b06a2015-09-22 15:03:44 -0700691 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
692 MockUtils.checkIntentAction(
693 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
694 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
695 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100696 eq(AppOpsManager.OP_NONE),
697 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700698 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700699 eq(dpms.mHandler),
700 eq(Activity.RESULT_OK),
701 isNull(String.class),
702 isNull(Bundle.class));
703
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700704 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800705 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
706 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700707
708 // Again broadcast from saveSettingsLocked().
709 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
710 MockUtils.checkIntentAction(
711 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
712 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
713
714 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700715 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700716
Sudheer Shanka101c3532018-01-08 16:28:42 -0800717 public void testRemoveActiveAdmin_multipleAdminsInUser() {
718 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
719 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
720
721 // Add admin1.
722 dpm.setActiveAdmin(admin1, /* replace =*/ false);
723
724 assertTrue(dpm.isAdminActive(admin1));
725 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
726
727 // Add admin2.
728 dpm.setActiveAdmin(admin2, /* replace =*/ false);
729
730 assertTrue(dpm.isAdminActive(admin2));
731 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
732
733 // Broadcast from saveSettingsLocked().
734 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
735 MockUtils.checkIntentAction(
736 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
737 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
738
739 // Remove. No permissions, but same user, so it'll work.
740 mContext.callerPermissions.clear();
741 dpm.removeActiveAdmin(admin1);
742
743 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
744 MockUtils.checkIntentAction(
745 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
746 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
747 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100748 eq(AppOpsManager.OP_NONE),
749 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800750 any(BroadcastReceiver.class),
751 eq(dpms.mHandler),
752 eq(Activity.RESULT_OK),
753 isNull(String.class),
754 isNull(Bundle.class));
755
756 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
757 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800758 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800759 eq(DpmMockContext.CALLER_USER_HANDLE));
760
761 // Again broadcast from saveSettingsLocked().
762 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
763 MockUtils.checkIntentAction(
764 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
765 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
766 }
767
768 /**
769 * Test for:
770 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
771 */
772 public void testForceRemoveActiveAdmin() throws Exception {
773 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
774
775 // Add admin.
776 setupPackageInPackageManager(admin1.getPackageName(),
777 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
778 /* appId= */ 10138,
779 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
780 dpm.setActiveAdmin(admin1, /* replace =*/ false);
781 assertTrue(dpm.isAdminActive(admin1));
782
783 // Calling from a non-shell uid should fail with a SecurityException
784 mContext.binder.callingUid = 123456;
785 assertExpectException(SecurityException.class,
786 /* messageRegex =*/ "Non-shell user attempted to call",
787 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
788
789 mContext.binder.callingUid = Process.SHELL_UID;
790 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
791
792 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
793 // Verify
794 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
795 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
796 null, DpmMockContext.CALLER_USER_HANDLE);
797 }
798
Makoto Onukib643fb02015-09-22 15:03:44 -0700799 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100800 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
801 *
802 * Validates that when the password history length is set, it is persisted after rebooting
803 */
804 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
805 int passwordHistoryLength = 2;
806
807 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
808 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
809 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
810
811 // Install admin1 on system user.
812 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
813
814 // Set admin1 to active admin and device owner
815 dpm.setActiveAdmin(admin1, false);
816 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
817
818 // Save password history length
819 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
820
821 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
822
823 initializeDpms();
824 reset(mContext.spiedContext);
825
826 // Password history length should persist after rebooted
827 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
828 }
829
830 /**
831 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000832 *
833 * Validates that when the password for a user changes, the notification broadcast intent
834 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
835 * addition to ones in the original user.
836 */
837 public void testSetActivePasswordState_sendToProfiles() throws Exception {
838 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
839
840 final int MANAGED_PROFILE_USER_ID = 78;
841 final int MANAGED_PROFILE_ADMIN_UID =
842 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
843
Robin Leed2a73ed2016-12-19 09:07:16 +0000844 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
845 mContext.packageName = admin1.getPackageName();
Robin Leed2a73ed2016-12-19 09:07:16 +0000846
847 // Add a managed profile belonging to the system user.
848 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
849
850 // Change the parent user's password.
851 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
852
Eran Messeri6ad0e192019-12-01 20:01:21 +0000853 // The managed profile owner should receive this broadcast.
Robin Leed2a73ed2016-12-19 09:07:16 +0000854 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
855 intent.setComponent(admin1);
856 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
857
858 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
859 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100860 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
861 eq(null),
862 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000863 }
864
865 /**
Rubin Xu19854862019-08-15 16:37:23 +0100866 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000867 *
868 * Validates that when the password for a managed profile changes, the notification broadcast
869 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
870 * its parent.
871 */
872 public void testSetActivePasswordState_notSentToParent() throws Exception {
873 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
874
875 final int MANAGED_PROFILE_USER_ID = 78;
876 final int MANAGED_PROFILE_ADMIN_UID =
877 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
878
Eran Messeri6ad0e192019-12-01 20:01:21 +0000879 // Configure system as having separate profile challenge.
Robin Leed2a73ed2016-12-19 09:07:16 +0000880 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
881 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100882 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000883 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
Robin Leed2a73ed2016-12-19 09:07:16 +0000884
885 // Add a managed profile belonging to the system user.
886 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
887
888 // Change the profile's password.
889 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
890
891 // Both the device owner and the managed profile owner should receive this broadcast.
892 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
893 intent.setComponent(admin1);
894 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
895
896 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
897 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100898 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
899 eq(null),
900 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000901 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
902 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100903 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
904 eq(null),
905 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000906 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100907
Robin Leed2a73ed2016-12-19 09:07:16 +0000908 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000909 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700910 */
911 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000912 setDeviceOwner();
913
914 // Try to set a profile owner on the same user, which should fail.
915 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
916 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100917 assertExpectException(IllegalStateException.class,
918 /* messageRegex= */ "already has a device owner",
919 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000920
921 // DO admin can't be deactivated.
922 dpm.removeActiveAdmin(admin1);
923 assertTrue(dpm.isAdminActive(admin1));
924
925 // TODO Test getDeviceOwnerName() too. To do so, we need to change
926 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
927 }
928
929 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700930 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800931 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700932 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
933 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
934
Makoto Onukid932f762015-09-29 16:53:38 -0700935 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700936 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
937
Makoto Onukid932f762015-09-29 16:53:38 -0700938 // Make sure admin1 is installed on system user.
939 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700940
Makoto Onukic8a5a552015-11-19 14:29:12 -0800941 // Check various get APIs.
942 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
943
Makoto Onukib643fb02015-09-22 15:03:44 -0700944 // DO needs to be an DA.
945 dpm.setActiveAdmin(admin1, /* replace =*/ false);
946
947 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700948 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700949
Makoto Onukic8a5a552015-11-19 14:29:12 -0800950 // getDeviceOwnerComponent should return the admin1 component.
951 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
952 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
953
954 // Check various get APIs.
955 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
956
957 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
958 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
959 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
960 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
961
962 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
963
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000964 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100965 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000966 eq(admin1.getPackageName()));
967
Eran Messeri6ad0e192019-12-01 20:01:21 +0000968 verify(getServices().userManager, times(1)).setUserRestriction(
969 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
970 eq(true), eq(UserHandle.SYSTEM));
971
Makoto Onukib643fb02015-09-22 15:03:44 -0700972 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
973 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
974 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
975
Makoto Onukic8a5a552015-11-19 14:29:12 -0800976 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700977 }
978
Makoto Onukic8a5a552015-11-19 14:29:12 -0800979 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
980 final int origCallingUser = mContext.binder.callingUid;
981 final List origPermissions = new ArrayList(mContext.callerPermissions);
982 mContext.callerPermissions.clear();
983
984 mContext.callerPermissions.add(permission.MANAGE_USERS);
985
986 mContext.binder.callingUid = Process.SYSTEM_UID;
987
988 // TODO Test getDeviceOwnerName() too. To do so, we need to change
989 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
990 if (hasDeviceOwner) {
991 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
992 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
993 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
994
995 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
996 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
997 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
998 } else {
999 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1000 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1001 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1002
1003 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1004 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1005 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1006 }
1007
1008 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1009 if (hasDeviceOwner) {
1010 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1011 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1012 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1013
1014 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1015 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1016 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1017 } else {
1018 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1019 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1020 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1021
1022 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1023 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1024 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1025 }
1026
1027 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1028 // Still with MANAGE_USERS.
1029 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1030 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1031 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1032
1033 if (hasDeviceOwner) {
1034 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1035 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1036 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1037 } else {
1038 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1039 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1040 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1041 }
1042
1043 mContext.binder.callingUid = Process.SYSTEM_UID;
1044 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1045 // System can still call "OnAnyUser" without MANAGE_USERS.
1046 if (hasDeviceOwner) {
1047 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1048 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1049 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1050
1051 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1052 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1053 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1054 } else {
1055 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1056 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1057 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1058
1059 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1060 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1061 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1062 }
1063
1064 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1065 // Still no MANAGE_USERS.
1066 if (hasDeviceOwner) {
1067 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1068 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1069 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1070 } else {
1071 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1072 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1073 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1074 }
1075
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001076 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1077 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1078 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1079 dpm::getDeviceOwnerComponentOnAnyUser);
1080 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1081 dpm::getDeviceOwnerUserId);
1082 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1083 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001084
1085 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1086 // Still no MANAGE_USERS.
1087 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1088 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1089 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1090
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001091 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1092 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1093 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1094 dpm::getDeviceOwnerComponentOnAnyUser);
1095 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1096 dpm::getDeviceOwnerUserId);
1097 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1098 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001099
1100 // Restore.
1101 mContext.binder.callingUid = origCallingUser;
1102 mContext.callerPermissions.addAll(origPermissions);
1103 }
1104
1105
Makoto Onukib643fb02015-09-22 15:03:44 -07001106 /**
1107 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1108 */
1109 public void testSetDeviceOwner_noSuchPackage() {
1110 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001111 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001112 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1113 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1114
1115 // Call from a process on the system user.
1116 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1117
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001118 assertExpectException(IllegalArgumentException.class,
1119 /* messageRegex= */ "Invalid component",
1120 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001121 }
1122
1123 public void testSetDeviceOwner_failures() throws Exception {
1124 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1125 }
1126
Makoto Onukia52562c2015-10-01 16:12:31 -07001127 public void testClearDeviceOwner() throws Exception {
1128 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001129 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1131 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1132
1133 // Set admin1 as a DA to the secondary user.
1134 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1135
1136 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1137
1138 // Set admin 1 as the DO to the system user.
1139
1140 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1141 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1142 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1143 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1144
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001145 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001146 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001147 eq(admin1.getPackageName()));
1148
Makoto Onukic8a5a552015-11-19 14:29:12 -08001149 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001150
Makoto Onuki90b89652016-01-28 14:44:18 -08001151 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001152 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001153 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001154
1155 assertTrue(dpm.isAdminActive(admin1));
1156 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1157
Makoto Onukia52562c2015-10-01 16:12:31 -07001158 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001159 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001160
1161 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001162 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1163 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001164
1165 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001166 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001167 assertExpectException(IllegalStateException.class,
1168 /* messageRegex= */ "User must be running and unlocked",
1169 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001170
Pavel Grafov75c0a892017-05-18 17:28:27 +01001171 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001172 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1173
1174 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001175 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001176
Pavel Grafov75c0a892017-05-18 17:28:27 +01001177 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001178 eq(false),
1179 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1180
Pavel Grafov75c0a892017-05-18 17:28:27 +01001181 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001182 eq(UserHandle.USER_SYSTEM), MockUtils.checkUserRestrictions(),
1183 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Makoto Onuki90b89652016-01-28 14:44:18 -08001184
Sudheer Shanka101c3532018-01-08 16:28:42 -08001185 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1186 null, UserHandle.USER_SYSTEM);
1187
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001188 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001189
1190 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1191 // and once for clearing it.
1192 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1193 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1194 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001195 // TODO Check other calls.
1196 }
1197
Pavel Grafov775b26d82019-10-30 13:29:01 +00001198 public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1199 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1200 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1201
1202 // Set admin1 as a DA to the secondary user.
1203 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1204 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1205 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1206 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1207
1208 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1209 eq(UserHandle.USER_SYSTEM), eq(false));
1210
1211 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1212
1213 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1214 eq(UserHandle.USER_SYSTEM), eq(true));
1215 }
1216
1217 public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1218 setAsProfileOwner(admin1);
1219
1220 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1221 eq(DpmMockContext.CALLER_USER_HANDLE), eq(false));
1222
1223 dpm.clearProfileOwner(admin1);
1224
1225 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1226 eq(DpmMockContext.CALLER_USER_HANDLE), eq(true));
1227 }
1228
Makoto Onukia52562c2015-10-01 16:12:31 -07001229 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1230 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001231 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1233 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1234
1235 // Set admin1 as a DA to the secondary user.
1236 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1237
1238 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1239
1240 // Set admin 1 as the DO to the system user.
1241
1242 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1243 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1244 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1245 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1246
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001247 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001248 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001249 eq(admin1.getPackageName()));
1250
Makoto Onukic8a5a552015-11-19 14:29:12 -08001251 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001252
1253 // Now call clear from the secondary user, which should throw.
1254 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1255
1256 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001257 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001258 eq(admin1.getPackageName()),
1259 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001260 assertExpectException(SecurityException.class,
1261 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1262 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001263
Makoto Onukic8a5a552015-11-19 14:29:12 -08001264 // DO shouldn't be removed.
1265 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001266 }
1267
Alex Johnston63220932019-09-26 10:10:51 +01001268 /**
1269 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1270 *
1271 * Validates that when the device owner is removed, the reset password token is cleared
1272 */
1273 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1274 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1275 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1276 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1277
1278 // Install admin1 on system user
1279 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1280
1281 // Set admin1 to active admin and device owner
1282 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1283 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1284
1285 // Add reset password token
1286 final long handle = 12000;
1287 final byte[] token = new byte[32];
1288 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1289 nullable(EscrowTokenStateChangeCallback.class)))
1290 .thenReturn(handle);
1291 assertTrue(dpm.setResetPasswordToken(admin1, token));
1292
1293 // Assert reset password token is active
1294 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1295 eq(UserHandle.USER_SYSTEM)))
1296 .thenReturn(true);
1297 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1298
1299 // Remove the device owner
1300 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1301
1302 // Verify password reset password token was removed
1303 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1304 eq(UserHandle.USER_SYSTEM));
1305 }
1306
Makoto Onukib643fb02015-09-22 15:03:44 -07001307 public void testSetProfileOwner() throws Exception {
1308 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001309
Makoto Onuki90b89652016-01-28 14:44:18 -08001310 // PO admin can't be deactivated.
1311 dpm.removeActiveAdmin(admin1);
1312 assertTrue(dpm.isAdminActive(admin1));
1313
Makoto Onuki803d6752015-10-30 12:58:39 -07001314 // Try setting DO on the same user, which should fail.
1315 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001316 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1317 runAsCaller(mServiceContext, dpms, dpm -> {
1318 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001319 assertExpectException(IllegalStateException.class,
1320 /* messageRegex= */ "already has a profile owner",
1321 () -> dpm.setDeviceOwner(admin2, "owner-name",
1322 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001323 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001324 }
1325
Makoto Onuki90b89652016-01-28 14:44:18 -08001326 public void testClearProfileOwner() throws Exception {
1327 setAsProfileOwner(admin1);
1328
1329 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1330
1331 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1332 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1333
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001334 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001335 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001336 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001337 assertExpectException(IllegalStateException.class,
1338 /* messageRegex= */ "User must be running and unlocked",
1339 () -> dpm.clearProfileOwner(admin1));
1340
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001341 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001342 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001343 dpm.clearProfileOwner(admin1);
1344
1345 // Check
1346 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001347 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001348 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1349 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001350 }
1351
Makoto Onukib643fb02015-09-22 15:03:44 -07001352 public void testSetProfileOwner_failures() throws Exception {
1353 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1354 }
1355
Makoto Onukia52562c2015-10-01 16:12:31 -07001356 public void testGetDeviceOwnerAdminLocked() throws Exception {
1357 checkDeviceOwnerWithMultipleDeviceAdmins();
1358 }
1359
1360 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1361 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1362 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1363 // make sure it gets the right component from the right user.
1364
1365 final int ANOTHER_USER_ID = 100;
1366 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1367
Alex Johnston755e3772019-11-29 03:27:22 +00001368 getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001369
1370 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001371 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001372 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1373 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1374
1375 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1376
Pavel Grafov75c0a892017-05-18 17:28:27 +01001377 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001378
Makoto Onukia52562c2015-10-01 16:12:31 -07001379 // Make sure the admin packge is installed to each user.
1380 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1381 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1382
1383 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1384 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1385
1386 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1387
1388
1389 // Set active admins to the users.
1390 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1391 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1392
1393 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1394 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1395
1396 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1397
1398 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001399 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001400 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1401
Makoto Onukic8a5a552015-11-19 14:29:12 -08001402 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001403
1404 // Then check getDeviceOwnerAdminLocked().
Alex Johnstoncd5bb5b2020-03-19 18:50:19 +00001405 assertEquals(admin2, getDeviceOwner().info.getComponent());
1406 assertEquals(DpmMockContext.CALLER_UID, getDeviceOwner().getUid());
Makoto Onukia52562c2015-10-01 16:12:31 -07001407 }
1408
1409 /**
1410 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001411 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1412 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001413 *
1414 * We didn't use to persist the DO component class name, but now we do, and the above method
1415 * finds the right component from a package name upon migration.
1416 */
1417 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001418 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001419 checkDeviceOwnerWithMultipleDeviceAdmins();
1420
1421 // Overwrite the device owner setting and clears the clas name.
1422 dpms.mOwners.setDeviceOwner(
1423 new ComponentName(admin2.getPackageName(), ""),
1424 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1425 dpms.mOwners.writeDeviceOwner();
1426
1427 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001428 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001429
1430 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001431 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001432 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001433 initializeDpms();
1434
1435 // Now the DO component name is a full name.
1436 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1437 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001438 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001439 }
1440
Makoto Onukib643fb02015-09-22 15:03:44 -07001441 public void testSetGetApplicationRestriction() {
1442 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001443 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001444
1445 {
1446 Bundle rest = new Bundle();
1447 rest.putString("KEY_STRING", "Foo1");
1448 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1449 }
1450
1451 {
1452 Bundle rest = new Bundle();
1453 rest.putString("KEY_STRING", "Foo2");
1454 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1455 }
1456
1457 {
1458 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1459 assertNotNull(returned);
1460 assertEquals(returned.size(), 1);
1461 assertEquals(returned.get("KEY_STRING"), "Foo1");
1462 }
1463
1464 {
1465 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1466 assertNotNull(returned);
1467 assertEquals(returned.size(), 1);
1468 assertEquals(returned.get("KEY_STRING"), "Foo2");
1469 }
1470
1471 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1472 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1473 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001474
Edman Anjosf9946772016-11-28 16:35:15 +01001475 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001476 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1477 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001478 *
1479 * @param packageName the name of the package to be setup
1480 * @param appId the application ID to be given to the package
1481 * @return the UID of the package as known by the mock package manager
1482 */
1483 private int setupPackageInPackageManager(final String packageName, final int appId)
1484 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001485 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001486 ApplicationInfo.FLAG_HAS_CODE);
1487 }
1488
1489 /**
1490 * Setup a package in the package manager mock. Useful for faking installed applications.
1491 *
1492 * @param packageName the name of the package to be setup
1493 * @param userId the user id where the package will be "installed"
1494 * @param appId the application ID to be given to the package
1495 * @param flags flags to set in the ApplicationInfo for this package
1496 * @return the UID of the package as known by the mock package manager
1497 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001498 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1499 int flags) throws Exception {
1500 final int uid = UserHandle.getUid(userId, appId);
1501 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001502 final PackageInfo pi = new PackageInfo();
1503 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001504 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001505 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001506 eq(packageName),
1507 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001508 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001509 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001510 eq(packageName),
1511 anyInt(),
1512 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001513 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001514 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001515 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001516 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001517 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001518 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001519 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001520 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001521 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001522 return uid;
1523 }
1524
Robin Lee7f5c91c2017-02-08 21:27:02 +00001525 public void testCertificateDisclosure() throws Exception {
1526 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1527 final UserHandle user = UserHandle.of(userId);
1528
1529 mContext.applicationInfo = new ApplicationInfo();
1530 mContext.callerPermissions.add(permission.MANAGE_USERS);
1531 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001532 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001533 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1534
Robin Leeabaa0692017-02-20 20:54:22 +00001535 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1536 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001537
1538 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1539 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1540
1541 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001542 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001543 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001544 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001545 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001546 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001547 .cancelAsUser(anyString(), anyInt(), eq(user));
1548
1549 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001550 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001551 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001552 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1553 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001554 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001555 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001556 .notifyAsUser(anyString(), anyInt(), argThat(
1557 new BaseMatcher<Notification>() {
1558 @Override
1559 public boolean matches(Object item) {
1560 final Notification noti = (Notification) item;
1561 return TEST_STRING.equals(
1562 noti.extras.getString(Notification.EXTRA_TITLE));
1563 }
1564 @Override
1565 public void describeTo(Description description) {
1566 description.appendText(
1567 "Notification{title=\"" + TEST_STRING + "\"}");
1568 }
1569 }), eq(user));
1570 }
1571
Edman Anjosf9946772016-11-28 16:35:15 +01001572 /**
1573 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1574 * privileges can acually be exercised by a delegate are not covered here.
1575 */
1576 public void testDelegation() throws Exception {
1577 setAsProfileOwner(admin1);
1578
1579 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1580
1581 // Given two packages
1582 final String CERT_DELEGATE = "com.delegate.certs";
1583 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1584 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1585 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1586 20989);
1587
1588 // On delegation
1589 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1590 mContext.packageName = admin1.getPackageName();
1591 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1592 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1593
1594 // DPMS correctly stores and retrieves the delegates
1595 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1596 assertEquals(2, policy.mDelegationMap.size());
1597 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1598 DELEGATION_CERT_INSTALL);
1599 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1600 DELEGATION_CERT_INSTALL);
1601 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1602 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1603 DELEGATION_APP_RESTRICTIONS);
1604 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1605 DELEGATION_APP_RESTRICTIONS);
1606 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1607
1608 // On calling install certificate APIs from an unauthorized process
1609 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1610 mContext.packageName = RESTRICTIONS_DELEGATE;
1611
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001612 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1613 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001614
1615 // On calling install certificate APIs from an authorized process
1616 mContext.binder.callingUid = CERT_DELEGATE_UID;
1617 mContext.packageName = CERT_DELEGATE;
1618
1619 // DPMS executes without a SecurityException
1620 try {
1621 dpm.installCaCert(null, null);
1622 } catch (SecurityException unexpected) {
1623 fail("Threw SecurityException on authorized access");
1624 } catch (NullPointerException expected) {
1625 }
1626
1627 // On removing a delegate
1628 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1629 mContext.packageName = admin1.getPackageName();
1630 dpm.setCertInstallerPackage(admin1, null);
1631
1632 // DPMS does not allow access to ex-delegate
1633 mContext.binder.callingUid = CERT_DELEGATE_UID;
1634 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001635 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1636 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001637
1638 // But still allows access to other existing delegates
1639 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1640 mContext.packageName = RESTRICTIONS_DELEGATE;
1641 try {
1642 dpm.getApplicationRestrictions(null, "pkg");
1643 } catch (SecurityException expected) {
1644 fail("Threw SecurityException on authorized access");
1645 }
1646 }
1647
Esteban Talaverabf60f722015-12-10 16:26:44 +00001648 public void testApplicationRestrictionsManagingApp() throws Exception {
1649 setAsProfileOwner(admin1);
1650
Rubin Xued1928a2016-02-11 17:23:06 +00001651 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001652 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001653 final String nonDelegateExceptionMessageRegex =
1654 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001655 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001656 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1657 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001658
Esteban Talaverabf60f722015-12-10 16:26:44 +00001659 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1660 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001661 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1662 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001663 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001664 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001665 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001666 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1667 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001668
1669 // Check via the profile owner that no restrictions were set.
1670 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001671 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001672 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1673
Rubin Xued1928a2016-02-11 17:23:06 +00001674 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001675 assertExpectException(PackageManager.NameNotFoundException.class,
1676 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1677 () -> dpm.setApplicationRestrictionsManagingPackage(
1678 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001679
Esteban Talaverabf60f722015-12-10 16:26:44 +00001680 // Let appRestrictionsManagerPackage manage app restrictions
1681 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1682 assertEquals(appRestrictionsManagerPackage,
1683 dpm.getApplicationRestrictionsManagingPackage(admin1));
1684
1685 // Now that package should be able to set and retrieve app restrictions.
1686 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001687 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001688 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1689 dpm.setApplicationRestrictions(null, "pkg1", rest);
1690 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1691 assertEquals(1, returned.size(), 1);
1692 assertEquals("Foo1", returned.get("KEY_STRING"));
1693
1694 // The same app running on a separate user shouldn't be able to manage app restrictions.
1695 mContext.binder.callingUid = UserHandle.getUid(
1696 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1697 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001698 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1699 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001700
1701 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1702 // too.
1703 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001704 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001705 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1706 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1707 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1708
1709 // Removing the ability for the package to manage app restrictions.
1710 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1711 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1712 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001713 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001714 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001715 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1716 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001717 }
1718
Makoto Onukia4f11972015-10-01 13:19:58 -07001719 public void testSetUserRestriction_asDo() throws Exception {
1720 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001721 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001722 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1723 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1724
1725 // First, set DO.
1726
1727 // Call from a process on the system user.
1728 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1729
1730 // Make sure admin1 is installed on system user.
1731 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001732
1733 // Call.
1734 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001735 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001736 UserHandle.USER_SYSTEM));
1737
Esteban Talavera548a04b2016-12-20 15:22:30 +00001738 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001739 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740
1741 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001743 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001744 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001745 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001746 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747
Makoto Onukia4f11972015-10-01 13:19:58 -07001748 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001749 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001750 eq(UserHandle.USER_SYSTEM),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001751 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1752 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM,
1753 UserManager.DISALLOW_OUTGOING_CALLS),
1754 eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001755 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001756
Makoto Onuki068c54a2015-10-13 14:34:03 -07001757 DpmTestUtils.assertRestrictions(
1758 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstoncd5bb5b2020-03-19 18:50:19 +00001760 getDeviceOwner().ensureUserRestrictions()
Makoto Onuki068c54a2015-10-13 14:34:03 -07001761 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001762 DpmTestUtils.assertRestrictions(
1763 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001765 dpm.getUserRestrictions(admin1)
1766 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001767
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001769 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001770 eq(UserHandle.USER_SYSTEM),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001771 MockUtils.checkUserRestrictions(),
1772 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM,
1773 UserManager.DISALLOW_OUTGOING_CALLS),
1774 eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001775 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001776
Makoto Onuki068c54a2015-10-13 14:34:03 -07001777 DpmTestUtils.assertRestrictions(
1778 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstoncd5bb5b2020-03-19 18:50:19 +00001779 getDeviceOwner().ensureUserRestrictions()
Makoto Onuki068c54a2015-10-13 14:34:03 -07001780 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001781 DpmTestUtils.assertRestrictions(
1782 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1783 dpm.getUserRestrictions(admin1)
1784 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001785
1786 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001787 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001788 eq(UserHandle.USER_SYSTEM),
1789 MockUtils.checkUserRestrictions(),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001790 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001791 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001792
Esteban Talavera548a04b2016-12-20 15:22:30 +00001793 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001794
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001795 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1796 // DO sets them, the scope is global.
1797 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001798 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001800 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001801 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001802 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001803 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001804 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001805 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001806
1807 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1808 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001809 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001810
1811 // More tests.
1812 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001813 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001814 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001815 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001816 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001817 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001818
1819 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001820 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001821 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001822 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001823 UserManager.DISALLOW_ADD_USER),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001824 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001825 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001826
1827 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001828 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001829 eq(UserHandle.USER_SYSTEM),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001830 // DISALLOW_CAMERA will be applied globally.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001832 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_CAMERA),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001833 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM), eq(true));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001834 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001835 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836
Alex Johnstoncd5bb5b2020-03-19 18:50:19 +00001837 private DevicePolicyManagerService.ActiveAdmin getDeviceOwner() {
1838 ComponentName component = dpms.mOwners.getDeviceOwnerComponent();
1839 DevicePolicyManagerService.DevicePolicyData policy =
1840 dpms.getUserData(dpms.mOwners.getDeviceOwnerUserId());
1841 for (DevicePolicyManagerService.ActiveAdmin admin : policy.mAdminList) {
1842 if (component.equals(admin.info.getComponent())) {
1843 return admin;
1844 }
1845 }
1846 return null;
1847 }
1848
Eric Sandnessca5969d2018-08-10 13:28:46 +01001849 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1850 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1851 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001852
Eric Sandnessca5969d2018-08-10 13:28:46 +01001853 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1854 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001855
Eric Sandnessca5969d2018-08-10 13:28:46 +01001856 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1857 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1858 () -> dpm.setCameraDisabled(admin1, true));
1859 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1860
1861 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1862 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1863 () -> dpm.setKeyguardDisabledFeatures(admin1,
1864 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1865 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1866
1867 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1868 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1869 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1870 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1871
1872 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1873 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1874 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1875 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001876 }
1877
1878 public void testSetUserRestriction_asPo() {
1879 setAsProfileOwner(admin1);
1880
Makoto Onuki068c54a2015-10-13 14:34:03 -07001881 DpmTestUtils.assertRestrictions(
1882 DpmTestUtils.newRestrictions(),
1883 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1884 .ensureUserRestrictions()
1885 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001886
1887 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001888 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001889 eq(DpmMockContext.CALLER_USER_HANDLE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001890 MockUtils.checkUserRestrictions(),
1891 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE,
1892 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
1893 eq(false));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001894
Makoto Onukia4f11972015-10-01 13:19:58 -07001895 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001896 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001897 eq(DpmMockContext.CALLER_USER_HANDLE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001898 MockUtils.checkUserRestrictions(),
1899 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE,
1900 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001901 UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001902 eq(false));
Makoto Onukia4f11972015-10-01 13:19:58 -07001903
Makoto Onuki068c54a2015-10-13 14:34:03 -07001904 DpmTestUtils.assertRestrictions(
1905 DpmTestUtils.newRestrictions(
1906 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1907 UserManager.DISALLOW_OUTGOING_CALLS
1908 ),
1909 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1910 .ensureUserRestrictions()
1911 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001912 DpmTestUtils.assertRestrictions(
1913 DpmTestUtils.newRestrictions(
1914 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
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_INSTALL_UNKNOWN_SOURCES);
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),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001923 MockUtils.checkUserRestrictions(),
1924 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE,
1925 UserManager.DISALLOW_OUTGOING_CALLS),
1926 eq(false));
Makoto Onuki068c54a2015-10-13 14:34:03 -07001927
1928 DpmTestUtils.assertRestrictions(
1929 DpmTestUtils.newRestrictions(
1930 UserManager.DISALLOW_OUTGOING_CALLS
1931 ),
1932 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1933 .ensureUserRestrictions()
1934 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001935 DpmTestUtils.assertRestrictions(
1936 DpmTestUtils.newRestrictions(
1937 UserManager.DISALLOW_OUTGOING_CALLS
1938 ),
1939 dpm.getUserRestrictions(admin1)
1940 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001941
1942 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001943 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001944 eq(DpmMockContext.CALLER_USER_HANDLE),
1945 MockUtils.checkUserRestrictions(),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001946 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE), eq(false));
Makoto Onukia4f11972015-10-01 13:19:58 -07001947
Makoto Onuki068c54a2015-10-13 14:34:03 -07001948 DpmTestUtils.assertRestrictions(
1949 DpmTestUtils.newRestrictions(),
1950 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1951 .ensureUserRestrictions()
1952 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001953 DpmTestUtils.assertRestrictions(
1954 DpmTestUtils.newRestrictions(),
1955 dpm.getUserRestrictions(admin1)
1956 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001957
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001958 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1959 // though when DO sets them they'll be applied globally.
1960 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001961
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001962 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001963 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001964 eq(DpmMockContext.CALLER_USER_HANDLE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001965 MockUtils.checkUserRestrictions(),
1966 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE,
1967 UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001968 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001969 eq(false));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001970
1971 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001972 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001973 eq(DpmMockContext.CALLER_USER_HANDLE),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00001974 MockUtils.checkUserRestrictions(),
1975 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE,
1976 UserManager.DISALLOW_ADJUST_VOLUME,
1977 UserManager.DISALLOW_UNMUTE_MICROPHONE,
1978 UserManager.DISALLOW_CAMERA),
1979 eq(false));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001980 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001981
Makoto Onukia4f11972015-10-01 13:19:58 -07001982 // TODO Make sure restrictions are written to the file.
1983 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001984
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001985 private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS =
1986 Sets.newSet(
1987 UserManager.DISALLOW_CONFIG_DATE_TIME,
1988 UserManager.DISALLOW_ADD_USER,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001989 UserManager.DISALLOW_BLUETOOTH_SHARING,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001990 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001991 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
1992 UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
1993 UserManager.DISALLOW_CONFIG_TETHERING,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001994 UserManager.DISALLOW_DATA_ROAMING,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001995 UserManager.DISALLOW_SAFE_BOOT,
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001996 UserManager.DISALLOW_SMS,
Alex Johnston9722abe2020-01-28 16:15:55 +00001997 UserManager.DISALLOW_USB_FILE_TRANSFER,
1998 UserManager.DISALLOW_AIRPLANE_MODE,
1999 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
Alex Johnston9722abe2020-01-28 16:15:55 +00002000 UserManager.DISALLOW_UNMUTE_MICROPHONE
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002001 );
2002
Alex Johnstonac42b162020-04-15 17:05:51 +01002003 private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS =
2004 Sets.newSet(
2005 UserManager.DISALLOW_CONFIG_BLUETOOTH,
2006 UserManager.DISALLOW_CONFIG_LOCATION,
2007 UserManager.DISALLOW_CONFIG_WIFI,
2008 UserManager.DISALLOW_CONTENT_CAPTURE,
2009 UserManager.DISALLOW_CONTENT_SUGGESTIONS,
2010 UserManager.DISALLOW_DEBUGGING_FEATURES,
2011 UserManager.DISALLOW_SHARE_LOCATION,
2012 UserManager.DISALLOW_OUTGOING_CALLS
2013 );
2014
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002015 public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00002016 final int MANAGED_PROFILE_ADMIN_UID =
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002017 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
Alex Johnston755e3772019-11-29 03:27:22 +00002018 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002019
Alex Johnston755e3772019-11-29 03:27:22 +00002020 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2021 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002022
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002023 when(getServices().userManager.getProfileParent(DpmMockContext.CALLER_USER_HANDLE))
Alex Johnston755e3772019-11-29 03:27:22 +00002024 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002025
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002026 for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
Alex Johnstonac42b162020-04-15 17:05:51 +01002027 addAndRemoveGlobalUserRestrictionOnParentDpm(restriction);
2028 }
2029 for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_LOCAL_RESTRICTIONS) {
2030 addAndRemoveLocalUserRestrictionOnParentDpm(restriction);
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002031 }
Alex Johnston51419382019-11-26 17:00:10 +00002032
Alex Johnston755e3772019-11-29 03:27:22 +00002033 parentDpm.setCameraDisabled(admin1, true);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002034 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002035 eq(DpmMockContext.CALLER_USER_HANDLE),
Alex Johnston755e3772019-11-29 03:27:22 +00002036 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002037 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE),
2038 eq(false));
2039 DpmTestUtils.assertRestrictions(
2040 DpmTestUtils.newRestrictions(UserManager.DISALLOW_CAMERA),
Alex Johnston9876c4f2020-03-03 10:42:26 +00002041 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
2042 .getParentActiveAdmin()
2043 .getEffectiveRestrictions()
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002044 );
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002045
Alex Johnston755e3772019-11-29 03:27:22 +00002046 parentDpm.setCameraDisabled(admin1, false);
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002047 DpmTestUtils.assertRestrictions(
2048 DpmTestUtils.newRestrictions(),
Alex Johnston9876c4f2020-03-03 10:42:26 +00002049 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
2050 .getParentActiveAdmin()
2051 .getEffectiveRestrictions()
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002052 );
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002053 reset(getServices().userManagerInternal);
2054 }
Esteban Talavera548a04b2016-12-20 15:22:30 +00002055
Alex Johnstonac42b162020-04-15 17:05:51 +01002056 private void addAndRemoveGlobalUserRestrictionOnParentDpm(String restriction) {
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002057 parentDpm.addUserRestriction(admin1, restriction);
2058 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2059 eq(DpmMockContext.CALLER_USER_HANDLE),
2060 MockUtils.checkUserRestrictions(restriction),
Alex Johnstonec6c3d32020-03-09 16:19:36 +00002061 MockUtils.checkUserRestrictions(DpmMockContext.CALLER_USER_HANDLE),
2062 eq(false));
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002063 parentDpm.clearUserRestriction(admin1, restriction);
2064 DpmTestUtils.assertRestrictions(
2065 DpmTestUtils.newRestrictions(),
Alex Johnston9876c4f2020-03-03 10:42:26 +00002066 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
2067 .getParentActiveAdmin()
2068 .getEffectiveRestrictions()
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002069 );
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002070 }
2071
Alex Johnstonac42b162020-04-15 17:05:51 +01002072 private void addAndRemoveLocalUserRestrictionOnParentDpm(String restriction) {
2073 parentDpm.addUserRestriction(admin1, restriction);
2074 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2075 eq(DpmMockContext.CALLER_USER_HANDLE),
2076 MockUtils.checkUserRestrictions(),
2077 MockUtils.checkUserRestrictions(UserHandle.USER_SYSTEM, restriction),
2078 eq(false));
2079 parentDpm.clearUserRestriction(admin1, restriction);
2080 DpmTestUtils.assertRestrictions(
2081 DpmTestUtils.newRestrictions(),
2082 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
2083 .getParentActiveAdmin()
2084 .getEffectiveRestrictions()
2085 );
2086 }
2087
Eran Messerice273df2019-12-17 13:14:45 +00002088 public void testNoDefaultEnabledUserRestrictions() throws Exception {
Esteban Talavera548a04b2016-12-20 15:22:30 +00002089 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2090 mContext.callerPermissions.add(permission.MANAGE_USERS);
2091 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2092 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2093
2094 // First, set DO.
2095
2096 // Call from a process on the system user.
2097 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2098
2099 // Make sure admin1 is installed on system user.
2100 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2101
2102 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2103 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
2104 UserHandle.USER_SYSTEM));
2105
Esteban Talavera548a04b2016-12-20 15:22:30 +00002106 assertNoDeviceOwnerRestrictions();
2107
Pavel Grafov75c0a892017-05-18 17:28:27 +01002108 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002109
Eran Messeri6ad0e192019-12-01 20:01:21 +00002110 // Ensure the DISALLOW_REMOVE_MANAGED_PROFILES restriction doesn't show up as a
2111 // restriction to the device owner.
2112 dpm.addUserRestriction(admin1, UserManager.DISALLOW_REMOVE_MANAGED_PROFILE);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002113 assertNoDeviceOwnerRestrictions();
Esteban Talavera548a04b2016-12-20 15:22:30 +00002114 }
2115
2116 private void assertNoDeviceOwnerRestrictions() {
2117 DpmTestUtils.assertRestrictions(
2118 DpmTestUtils.newRestrictions(),
Alex Johnston9876c4f2020-03-03 10:42:26 +00002119 getDeviceOwner().getEffectiveRestrictions()
Esteban Talavera548a04b2016-12-20 15:22:30 +00002120 );
2121 }
2122
Alex Johnston011f5c62019-12-18 17:05:57 +00002123 public void testSetFactoryResetProtectionPolicyWithDO() throws Exception {
2124 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2125 setupDeviceOwner();
2126
2127 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2128 DpmMockContext.CALLER_UID);
2129
2130 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2131 .setFactoryResetProtectionAccounts(new ArrayList<>())
Alex Johnston0f20b0e2020-02-13 16:54:35 +00002132 .setFactoryResetProtectionEnabled(false)
Alex Johnston011f5c62019-12-18 17:05:57 +00002133 .build();
2134 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2135
2136 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2137 assertThat(result).isEqualTo(policy);
2138 assertPoliciesAreEqual(policy, result);
2139
2140 verify(mContext.spiedContext).sendBroadcastAsUser(
2141 MockUtils.checkIntentAction(
2142 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
Alex Johnston090fa3c2020-02-06 17:48:56 +00002143 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
2144 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
Alex Johnston011f5c62019-12-18 17:05:57 +00002145 }
2146
2147 public void testSetFactoryResetProtectionPolicyFailWithPO() throws Exception {
2148 setupProfileOwner();
2149
2150 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
Alex Johnston0f20b0e2020-02-13 16:54:35 +00002151 .setFactoryResetProtectionEnabled(false)
Alex Johnston011f5c62019-12-18 17:05:57 +00002152 .build();
2153
2154 assertExpectException(SecurityException.class, null,
2155 () -> dpm.setFactoryResetProtectionPolicy(admin1, policy));
2156 }
2157
2158 public void testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice()
2159 throws Exception {
2160 setupProfileOwner();
2161 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2162
2163 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2164 DpmMockContext.CALLER_UID);
2165
2166 List<String> accounts = new ArrayList<>();
2167 accounts.add("Account 1");
2168 accounts.add("Account 2");
2169
2170 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2171 .setFactoryResetProtectionAccounts(accounts)
2172 .build();
2173
2174 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2175
2176 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2177 assertThat(result).isEqualTo(policy);
2178 assertPoliciesAreEqual(policy, result);
2179
2180 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
2181 MockUtils.checkIntentAction(
2182 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
2183 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2184 verify(mContext.spiedContext).sendBroadcastAsUser(
2185 MockUtils.checkIntentAction(
2186 DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED),
2187 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2188 verify(mContext.spiedContext).sendBroadcastAsUser(
2189 MockUtils.checkIntentAction(
2190 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
Alex Johnston090fa3c2020-02-06 17:48:56 +00002191 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
2192 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
Alex Johnston011f5c62019-12-18 17:05:57 +00002193 }
2194
2195 public void testGetFactoryResetProtectionPolicyWithFrpManagementAgent()
2196 throws Exception {
2197 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2198 setupDeviceOwner();
2199 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2200 DpmMockContext.CALLER_UID);
2201
2202 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2203 .setFactoryResetProtectionAccounts(new ArrayList<>())
Alex Johnston0f20b0e2020-02-13 16:54:35 +00002204 .setFactoryResetProtectionEnabled(false)
Alex Johnston011f5c62019-12-18 17:05:57 +00002205 .build();
2206
2207 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2208
2209 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2210 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2211 dpm.setActiveAdmin(admin1, /*replace=*/ false);
2212 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(null);
2213 assertThat(result).isEqualTo(policy);
2214 assertPoliciesAreEqual(policy, result);
2215
2216 verify(mContext.spiedContext).sendBroadcastAsUser(
2217 MockUtils.checkIntentAction(
2218 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
Alex Johnston090fa3c2020-02-06 17:48:56 +00002219 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
2220 eq(android.Manifest.permission.MANAGE_FACTORY_RESET_PROTECTION));
Alex Johnston011f5c62019-12-18 17:05:57 +00002221 }
2222
2223 private void assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy,
2224 FactoryResetProtectionPolicy actualPolicy) {
Alex Johnston0f20b0e2020-02-13 16:54:35 +00002225 assertThat(actualPolicy.isFactoryResetProtectionEnabled()).isEqualTo(
2226 expectedPolicy.isFactoryResetProtectionEnabled());
Alex Johnston011f5c62019-12-18 17:05:57 +00002227 assertAccountsAreEqual(expectedPolicy.getFactoryResetProtectionAccounts(),
2228 actualPolicy.getFactoryResetProtectionAccounts());
2229 }
2230
2231 private void assertAccountsAreEqual(List<String> expectedAccounts,
2232 List<String> actualAccounts) {
2233 assertThat(actualAccounts).containsExactlyElementsIn(expectedAccounts);
2234 }
2235
Alex Johnstonaf0aa252020-02-04 10:53:04 +00002236 public void testSetKeyguardDisabledFeaturesWithDO() throws Exception {
2237 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2238 setupDeviceOwner();
2239
2240 dpm.setKeyguardDisabledFeatures(admin1, DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2241
2242 assertThat(dpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2243 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2244 }
2245
2246 public void testSetKeyguardDisabledFeaturesWithPO() throws Exception {
2247 setupProfileOwner();
2248
2249 dpm.setKeyguardDisabledFeatures(admin1, DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT);
2250
2251 assertThat(dpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2252 DevicePolicyManager.KEYGUARD_DISABLE_FINGERPRINT);
2253 }
2254
2255 public void testSetKeyguardDisabledFeaturesWithPOOfOrganizationOwnedDevice()
2256 throws Exception {
2257 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
2258 final int MANAGED_PROFILE_ADMIN_UID =
2259 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2260 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2261
2262 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2263 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2264
2265 parentDpm.setKeyguardDisabledFeatures(admin1,
2266 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2267
2268 assertThat(parentDpm.getKeyguardDisabledFeatures(admin1)).isEqualTo(
2269 DevicePolicyManager.KEYGUARD_DISABLE_SECURE_CAMERA);
2270 }
2271
Alex Johnstona552dd62020-01-17 17:05:25 +00002272 public void testSetApplicationHiddenWithDO() throws Exception {
2273 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2274 setupDeviceOwner();
2275 mContext.packageName = admin1.getPackageName();
2276 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2277
2278 String packageName = "com.google.android.test";
2279
2280 dpm.setApplicationHidden(admin1, packageName, true);
2281 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2282 true, UserHandle.USER_SYSTEM);
2283
2284 dpm.setApplicationHidden(admin1, packageName, false);
2285 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2286 false, UserHandle.USER_SYSTEM);
2287
2288 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2289 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
2290 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2291 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2292 UserHandle.USER_SYSTEM);
2293 }
2294
2295 public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception {
2296 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
2297 final int MANAGED_PROFILE_ADMIN_UID =
2298 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2299 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2300
2301 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2302 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2303 mContext.packageName = admin1.getPackageName();
2304 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2305
2306 String packageName = "com.google.android.test";
2307
Alex Johnston05956bd2020-01-22 17:52:47 +00002308 ApplicationInfo applicationInfo = new ApplicationInfo();
2309 applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
Alex Johnstona552dd62020-01-17 17:05:25 +00002310 when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2311 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Alex Johnston05956bd2020-01-22 17:52:47 +00002312 when(getServices().ipackageManager.getApplicationInfo(packageName,
2313 PackageManager.MATCH_UNINSTALLED_PACKAGES, UserHandle.USER_SYSTEM)).thenReturn(
2314 applicationInfo);
Alex Johnstona552dd62020-01-17 17:05:25 +00002315
2316 parentDpm.setApplicationHidden(admin1, packageName, true);
2317 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2318 true, UserHandle.USER_SYSTEM);
2319
2320 parentDpm.setApplicationHidden(admin1, packageName, false);
2321 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2322 false, UserHandle.USER_SYSTEM);
2323 }
2324
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002325 public void testGetMacAddress() throws Exception {
2326 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2327 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2328 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2329
2330 // In this test, change the caller user to "system".
2331 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2332
2333 // Make sure admin1 is installed on system user.
2334 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2335
2336 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002337 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2338 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002339
2340 // DO needs to be an DA.
2341 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2342 assertTrue(dpm.isAdminActive(admin1));
2343
2344 // Test 2. Caller has DA, but not DO.
Eran Messeri6ba10db2019-12-04 15:53:27 +00002345 assertExpectException(SecurityException.class,
2346 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002347 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002348
2349 // Test 3. Caller has PO, but not DO.
2350 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Eran Messeri6ba10db2019-12-04 15:53:27 +00002351 assertExpectException(SecurityException.class,
2352 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002353 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002354
2355 // Remove PO.
2356 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002357 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002358 // Test 4, Caller is DO now.
2359 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2360
xshu425b9a62018-12-13 14:18:18 -08002361 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002362 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002363
xshu425b9a62018-12-13 14:18:18 -08002364 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2365 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002366 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002367
2368 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002369 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2370 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002371 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002372 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002373
Eran Messeri6ba10db2019-12-04 15:53:27 +00002374 public void testGetMacAddressByOrgOwnedPO() throws Exception {
2375 setupProfileOwner();
2376 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2377
2378 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2379 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
2380 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
2381 }
2382
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002383 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002384 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2385 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2386
2387 // In this test, change the caller user to "system".
2388 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2389
2390 // Make sure admin1 is installed on system user.
2391 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2392
2393 // Set admin1 as DA.
2394 dpm.setActiveAdmin(admin1, false);
2395 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002396 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2397 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002398
2399 // Set admin1 as PO.
2400 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002401 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2402 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002403
2404 // Remove PO and add DO.
2405 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002406 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002407 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2408
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002409 // admin1 is DO.
2410 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002411 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002412 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002413 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2414 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002415
2416 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002417 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002418 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002419 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2420 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002421
2422 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002423 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002424 dpm.reboot(admin1);
2425 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002426
2427 public void testSetGetSupportText() {
2428 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2429 dpm.setActiveAdmin(admin1, true);
2430 dpm.setActiveAdmin(admin2, true);
2431 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2432
2433 // Null default support messages.
2434 {
2435 assertNull(dpm.getLongSupportMessage(admin1));
2436 assertNull(dpm.getShortSupportMessage(admin1));
2437 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2438 assertNull(dpm.getShortSupportMessageForUser(admin1,
2439 DpmMockContext.CALLER_USER_HANDLE));
2440 assertNull(dpm.getLongSupportMessageForUser(admin1,
2441 DpmMockContext.CALLER_USER_HANDLE));
2442 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2443 }
2444
2445 // Only system can call the per user versions.
2446 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002447 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2448 () -> dpm.getShortSupportMessageForUser(admin1,
2449 DpmMockContext.CALLER_USER_HANDLE));
2450 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2451 () -> dpm.getLongSupportMessageForUser(admin1,
2452 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002453 }
2454
2455 // Can't set message for admin in another uid.
2456 {
2457 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002458 assertExpectException(SecurityException.class,
2459 /* messageRegex= */ "is not owned by uid",
2460 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002461 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2462 }
2463
2464 // Set/Get short returns what it sets and other admins text isn't changed.
2465 {
2466 final String supportText = "Some text to test with.";
2467 dpm.setShortSupportMessage(admin1, supportText);
2468 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2469 assertNull(dpm.getLongSupportMessage(admin1));
2470 assertNull(dpm.getShortSupportMessage(admin2));
2471
2472 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2473 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2474 DpmMockContext.CALLER_USER_HANDLE));
2475 assertNull(dpm.getShortSupportMessageForUser(admin2,
2476 DpmMockContext.CALLER_USER_HANDLE));
2477 assertNull(dpm.getLongSupportMessageForUser(admin1,
2478 DpmMockContext.CALLER_USER_HANDLE));
2479 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2480
2481 dpm.setShortSupportMessage(admin1, null);
2482 assertNull(dpm.getShortSupportMessage(admin1));
2483 }
2484
2485 // Set/Get long returns what it sets and other admins text isn't changed.
2486 {
2487 final String supportText = "Some text to test with.\nWith more text.";
2488 dpm.setLongSupportMessage(admin1, supportText);
2489 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2490 assertNull(dpm.getShortSupportMessage(admin1));
2491 assertNull(dpm.getLongSupportMessage(admin2));
2492
2493 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2494 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2495 DpmMockContext.CALLER_USER_HANDLE));
2496 assertNull(dpm.getLongSupportMessageForUser(admin2,
2497 DpmMockContext.CALLER_USER_HANDLE));
2498 assertNull(dpm.getShortSupportMessageForUser(admin1,
2499 DpmMockContext.CALLER_USER_HANDLE));
2500 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2501
2502 dpm.setLongSupportMessage(admin1, null);
2503 assertNull(dpm.getLongSupportMessage(admin1));
2504 }
2505 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002506
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002507 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002508 setAsProfileOwner(admin1);
2509
2510 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002511 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002512
2513 // Setup
2514 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2515 final String package1 = "com.example.one";
2516 final String package2 = "com.example.two";
2517 pkgsToRestrict.add(package1);
2518 pkgsToRestrict.add(package2);
2519 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2520 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002521 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002522
2523 // Verify
2524 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002525 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002526 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2527 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2528 eq(DpmMockContext.CALLER_USER_HANDLE));
2529
2530 // Setup
2531 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002532 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002533
2534 // Verify
2535 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002536 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002537 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2538 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2539 eq(DpmMockContext.CALLER_USER_HANDLE));
2540 }
2541
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002542 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002543 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2544 dpm.setActiveAdmin(admin1, true);
2545 assertTrue(dpm.isAdminActive(admin1));
2546 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2547
2548 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002549 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002550 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002551 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002552 }
2553
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002554 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002555 setAsProfileOwner(admin1);
2556
2557 // Setup
2558 final ArrayList<String> emptyList = new ArrayList<>();
2559 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2560 final String package1 = "com.example.one";
2561 final String package2 = "com.example.two";
2562 final String package3 = "com.example.three";
2563 pkgsToRestrict.add(package1);
2564 pkgsToRestrict.add(package2);
2565 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2566 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002567 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002568
2569 // Verify
2570 assertEquals(emptyList, excludedPkgs);
2571 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2572 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002573 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002574 DpmMockContext.CALLER_USER_HANDLE));
2575 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002576 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002577 DpmMockContext.CALLER_USER_HANDLE));
2578 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002579 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002580 DpmMockContext.CALLER_USER_HANDLE));
2581 }
2582
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002583 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002584 setAsProfileOwner(admin1);
2585 assertExpectException(SecurityException.class,
2586 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002587 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002588 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2589 dpm.clearProfileOwner(admin1);
2590
2591 setDeviceOwner();
2592 assertExpectException(SecurityException.class,
2593 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002594 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002595 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2596 clearDeviceOwner();
2597 }
2598
phweiss73145f42017-01-17 19:06:38 +01002599 public void testCreateAdminSupportIntent() throws Exception {
2600 // Setup device owner.
2601 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2602 setupDeviceOwner();
2603
2604 // Nonexisting permission returns null
2605 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2606 assertNull(intent);
2607
2608 // Existing permission that is not set returns null
2609 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2610 assertNull(intent);
2611
2612 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002613 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002614 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2615 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2616 .thenReturn(true);
2617 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2618 assertNull(intent);
2619
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002620 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2621 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2622 new UserManager.EnforcingUser(
2623 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2624 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002625 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002626 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002627 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2628 assertNotNull(intent);
2629 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2630 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2631 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002632 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002633 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2634 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2635
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002636 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2637 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002638
2639 // Camera is not disabled
2640 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2641 assertNull(intent);
2642
2643 // Camera is disabled
2644 dpm.setCameraDisabled(admin1, true);
2645 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2646 assertNotNull(intent);
2647 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2648 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2649
2650 // Screen capture is not disabled
2651 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2652 assertNull(intent);
2653
2654 // Screen capture is disabled
2655 dpm.setScreenCaptureDisabled(admin1, true);
2656 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2657 assertNotNull(intent);
2658 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2659 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2660
2661 // Same checks for different user
2662 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2663 // Camera should be disabled by device owner
2664 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2665 assertNotNull(intent);
2666 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2667 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2668 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2669 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2670 // ScreenCapture should not be disabled by device owner
2671 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2672 assertNull(intent);
2673 }
2674
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002675 /**
2676 * Test for:
2677 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002678 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002679 * {@link DevicePolicyManager#isAffiliatedUser}
2680 */
2681 public void testUserAffiliation() throws Exception {
2682 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2683 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2684 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2685
2686 // Check that the system user is unaffiliated.
2687 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2688 assertFalse(dpm.isAffiliatedUser());
2689
2690 // Set a device owner on the system user. Check that the system user becomes affiliated.
2691 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2692 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2693 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2694 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002695 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002696
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002697 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002698 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2699 setAsProfileOwner(admin2);
2700 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002701 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002702
2703 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2704 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002705 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002706 userAffiliationIds.add("red");
2707 userAffiliationIds.add("green");
2708 userAffiliationIds.add("blue");
2709 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002710 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002711 assertFalse(dpm.isAffiliatedUser());
2712
2713 // Have the device owner specify a set of affiliation ids that do not intersect with those
2714 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002715 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002716 deviceAffiliationIds.add("cyan");
2717 deviceAffiliationIds.add("yellow");
2718 deviceAffiliationIds.add("magenta");
2719 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2720 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002721 MoreAsserts.assertContentsInAnyOrder(
2722 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002723 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2724 assertFalse(dpm.isAffiliatedUser());
2725
2726 // Have the profile owner specify a set of affiliation ids that intersect with those
2727 // specified by the device owner. Check that the test user becomes affiliated.
2728 userAffiliationIds.add("yellow");
2729 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002730 MoreAsserts.assertContentsInAnyOrder(
2731 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002732 assertTrue(dpm.isAffiliatedUser());
2733
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002734 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002735 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002736 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002737 assertFalse(dpm.isAffiliatedUser());
2738
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002739 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2740 dpm.setAffiliationIds(admin2, userAffiliationIds);
2741 assertTrue(dpm.isAffiliatedUser());
2742 dpm.clearProfileOwner(admin2);
2743 assertFalse(dpm.isAffiliatedUser());
2744
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002745 // Check that the system user remains affiliated.
2746 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2747 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002748
2749 // Clear the device owner - the user becomes unaffiliated.
2750 clearDeviceOwner();
2751 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002752 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002753
2754 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002755 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002756 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2757 }
2758
2759 public void testSetUserProvisioningState_permission() throws Exception {
2760 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002761
2762 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2763 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2764 }
2765
2766 public void testSetUserProvisioningState_unprivileged() throws Exception {
2767 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002768 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2769 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2770 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002771 }
2772
2773 public void testSetUserProvisioningState_noManagement() {
2774 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002775 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002776 assertExpectException(IllegalStateException.class,
2777 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2778 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2779 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002780 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2781 }
2782
2783 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2784 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2785 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002786
2787 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2788 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2789 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2790 }
2791
2792 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2793 throws Exception {
2794 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2795 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002796
2797 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2798 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2799 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2800 }
2801
2802 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2803 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2804 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002805
2806 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2807 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2808 }
2809
2810 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2811 throws Exception {
2812 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002813
2814 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2815 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2816 DevicePolicyManager.STATE_USER_UNMANAGED);
2817 }
2818
2819 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2820 throws Exception {
2821 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002822
2823 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2824 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2825 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2826 }
2827
2828 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2829 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002830
2831 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2832 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2833 }
2834
2835 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2836 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002837
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002838 assertExpectException(IllegalStateException.class,
2839 /* messageRegex= */ "Cannot move to user provisioning state",
2840 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2841 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2842 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002843 }
2844
2845 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2846 throws Exception {
2847 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002848
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002849 assertExpectException(IllegalStateException.class,
2850 /* messageRegex= */ "Cannot move to user provisioning state",
2851 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2852 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2853 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002854 }
2855
2856 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002857 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2858 mContext.callerPermissions.add(permission.MANAGE_USERS);
2859
Alan Treadwayafad8782016-01-19 15:15:08 +00002860 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2861 for (int state : states) {
2862 dpm.setUserProvisioningState(state, userId);
2863 assertEquals(state, dpm.getUserProvisioningState());
2864 }
2865 }
2866
2867 private void setupProfileOwner() throws Exception {
2868 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2869
2870 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2871 dpm.setActiveAdmin(admin1, false);
2872 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2873
2874 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2875 }
2876
Alex Johnston8c503382019-11-19 11:12:15 +00002877 private void setupProfileOwnerOnUser0() throws Exception {
2878 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2879
2880 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2881 dpm.setActiveAdmin(admin1, false);
2882 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
2883
2884 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2885 }
2886
Alan Treadwayafad8782016-01-19 15:15:08 +00002887 private void setupDeviceOwner() throws Exception {
2888 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2889
2890 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2891 dpm.setActiveAdmin(admin1, false);
2892 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2893
2894 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2895 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002896
2897 public void testSetMaximumTimeToLock() {
2898 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2899
2900 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2901 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2902
Pavel Grafov75c0a892017-05-18 17:28:27 +01002903 reset(getServices().powerManagerInternal);
2904 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002905
2906 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002907 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2908 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002909 reset(getServices().powerManagerInternal);
2910 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002911
2912 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002913 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2914 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002915 reset(getServices().powerManagerInternal);
2916 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002917
2918 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002919 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2920 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002921 reset(getServices().powerManagerInternal);
2922 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002923
2924 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002925 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2926 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002927 reset(getServices().powerManagerInternal);
2928 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002929
2930 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002931 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2932 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002933 reset(getServices().powerManagerInternal);
2934 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002935
2936 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002937 reset(getServices().powerManagerInternal);
2938 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002939
Pavel Grafov28939982017-10-03 15:11:52 +01002940 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2941 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2942 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002943 reset(getServices().powerManagerInternal);
2944 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002945
2946 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002947 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2948 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002949 reset(getServices().powerManagerInternal);
2950 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002951
Pavel Grafov28939982017-10-03 15:11:52 +01002952 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002953 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002954 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2955 verifyStayOnWhilePluggedCleared(false);
2956 }
2957
Varun Shahb472b8f2019-09-23 23:01:06 -07002958 public void testIsActiveSupervisionApp() throws Exception {
2959 when(mServiceContext.resources
2960 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2961 .thenReturn(admin1.flattenToString());
2962
2963 final int PROFILE_USER = 15;
2964 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2965 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2966 mContext.binder.callingUid = PROFILE_ADMIN;
2967
2968 final DevicePolicyManagerInternal dpmi =
2969 LocalServices.getService(DevicePolicyManagerInternal.class);
2970 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2971 }
2972
Pavel Grafov28939982017-10-03 15:11:52 +01002973 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2974 // uses separate challenge.
2975 public void testSetMaximumTimeToLockProfile() throws Exception {
2976 final int PROFILE_USER = 15;
2977 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2978 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2979 mContext.binder.callingUid = PROFILE_ADMIN;
2980 final DevicePolicyManagerInternal dpmi =
2981 LocalServices.getService(DevicePolicyManagerInternal.class);
2982
2983 dpm.setMaximumTimeToLock(admin1, 0);
2984
2985 reset(getServices().powerManagerInternal);
2986 reset(getServices().settings);
2987
2988 // First add timeout for the profile.
2989 dpm.setMaximumTimeToLock(admin1, 10);
2990 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2991
2992 reset(getServices().powerManagerInternal);
2993 reset(getServices().settings);
2994
2995 // Add separate challenge
2996 when(getServices().lockPatternUtils
2997 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2998 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2999
3000 verifyScreenTimeoutCall(10L, PROFILE_USER);
3001 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
3002
3003 reset(getServices().powerManagerInternal);
3004 reset(getServices().settings);
3005
3006 // Remove the timeout.
3007 dpm.setMaximumTimeToLock(admin1, 0);
3008 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
3009 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
3010
3011 reset(getServices().powerManagerInternal);
3012 reset(getServices().settings);
3013
3014 // Add it back.
3015 dpm.setMaximumTimeToLock(admin1, 10);
3016 verifyScreenTimeoutCall(10L, PROFILE_USER);
3017 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
3018
3019 reset(getServices().powerManagerInternal);
3020 reset(getServices().settings);
3021
3022 // Remove separate challenge.
3023 reset(getServices().lockPatternUtils);
3024 when(getServices().lockPatternUtils
3025 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
3026 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01003027 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01003028
3029 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
3030 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
3031
3032 reset(getServices().powerManagerInternal);
3033 reset(getServices().settings);
3034
3035 // Remove the timeout.
3036 dpm.setMaximumTimeToLock(admin1, 0);
3037 verifyScreenTimeoutCall(null, PROFILE_USER);
3038 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003039 }
3040
Michal Karpinski943aabd2016-10-06 11:09:25 +01003041 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
3042 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3043 setupDeviceOwner();
3044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3045
Michal Karpinskid084ca52017-01-18 15:54:18 +00003046 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
3047 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
3048 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
3049 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
3050 - ONE_MINUTE;
3051
3052 // verify that the minimum timeout cannot be modified on user builds (system property is
3053 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01003054 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00003055
3056 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3057 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
3058 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
3059
Pavel Grafov75c0a892017-05-18 17:28:27 +01003060 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00003061
3062 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01003063 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00003064
Michal Karpinskid084ca52017-01-18 15:54:18 +00003065 // reset to default (0 means the admin is not participating, so default should be returned)
3066 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01003067
3068 // aggregation should be the default if unset by any admin
3069 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3070 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3071
3072 // admin not participating by default
3073 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3074
3075 //clamping from the top
3076 dpm.setRequiredStrongAuthTimeout(admin1,
3077 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
3078 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
3079 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3080 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3081 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3082
Michal Karpinskid084ca52017-01-18 15:54:18 +00003083 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01003084 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3085 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3086 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3087 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3088
3089 // clamping from the bottom
3090 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
3091 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3092 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3093
Michal Karpinskid084ca52017-01-18 15:54:18 +00003094 // values within range
3095 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
3096 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
3097 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
3098
3099 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3100 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
3101 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01003102
3103 // reset to default
3104 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3105 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3106 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3107 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3108
3109 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003110 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3111 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01003112 }
3113
Pavel Grafov28939982017-10-03 15:11:52 +01003114 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003115 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003116 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01003117 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003118 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003119 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01003120 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003121 }
Pavel Grafov28939982017-10-03 15:11:52 +01003122 }
3123
3124 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003125 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
3126 // UnfinishedVerificationException.
3127 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003128
Esteban Talavera01576862016-12-15 11:16:44 +00003129 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003130 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00003131 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003132 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003133 .thenReturn(false);
3134 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003135 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3136 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003137 .thenReturn(true);
3138 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3139
3140 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003141 }
Victor Chang3e794af2016-03-04 13:48:17 +00003142
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003143 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
3144 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003145 mContext.packageName = admin1.getPackageName();
3146 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003147 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003148 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003149 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3150 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3151 false);
3152 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3153 }
3154
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003155 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
3156 setup_DeviceAdminFeatureOff();
3157 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3158 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3159 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Yanli Wan01c92552019-11-18 16:07:54 -08003160 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3161 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003162 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3163 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3164 assertCheckProvisioningPreCondition(
3165 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3166 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3167 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3168 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3169 }
3170
Esteban Talavera01576862016-12-15 11:16:44 +00003171 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003172 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003173 .thenReturn(false);
3174 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003175 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3176 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003177 .thenReturn(true);
3178 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3179
3180 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003181 }
Victor Chang3e794af2016-03-04 13:48:17 +00003182
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003183 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
3184 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003185 mContext.packageName = admin1.getPackageName();
3186 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003187 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003188 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003189 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3190 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3191 false);
3192 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3193
3194 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003195 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00003196 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003197 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003198 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3199 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3200 true);
3201 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3202 }
3203
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003204 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
3205 setup_ManagedProfileFeatureOff();
3206 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3207 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3208 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003209 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3210 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003211 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3212 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3213 assertCheckProvisioningPreCondition(
3214 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3215 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3216 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3217 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3218
3219 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003221 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3222 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003223 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3224 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003225 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3226 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3227 assertCheckProvisioningPreCondition(
3228 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3229 DevicePolicyManager.CODE_OK);
3230 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3231 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3232 }
3233
Esteban Talavera01576862016-12-15 11:16:44 +00003234 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003235 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003236 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003237 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3238 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003239 .thenReturn(true);
3240 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
Eran Messeri957d31d2020-01-16 10:21:26 +00003241 when(getServices().userManager.getProfileParent(UserHandle.USER_SYSTEM)).thenReturn(null);
Victor Chang3e794af2016-03-04 13:48:17 +00003242
3243 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 }
Victor Chang3e794af2016-03-04 13:48:17 +00003245
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
3247 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003248 mContext.packageName = admin1.getPackageName();
3249 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003250 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003251 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003252 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3253 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3254 false /* because of non-split user */);
3255 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3256 false /* because of non-split user */);
3257 }
3258
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003259 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003260 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003261 setup_nonSplitUser_firstBoot_primaryUser();
3262 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3264 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003265 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3266 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003267 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3268 DevicePolicyManager.CODE_OK);
3269 assertCheckProvisioningPreCondition(
3270 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3271 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3272 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3273 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3274 }
3275
Esteban Talavera01576862016-12-15 11:16:44 +00003276 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003277 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003278 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003279 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3280 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003281 .thenReturn(true);
3282 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
Eran Messeri957d31d2020-01-16 10:21:26 +00003283 when(getServices().userManager.getProfileParent(UserHandle.USER_SYSTEM)).thenReturn(null);
Victor Chang3e794af2016-03-04 13:48:17 +00003284
3285 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003286 }
Victor Chang3e794af2016-03-04 13:48:17 +00003287
Nicolas Prevot45d29072017-01-18 16:11:19 +00003288 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
3289 setDeviceOwner();
3290 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3291 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3292 }
3293
3294 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3295 setup_nonSplitUser_withDo_primaryUser();
3296 final int MANAGED_PROFILE_USER_ID = 18;
3297 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003298 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003299 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003300 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003301 true)).thenReturn(true);
3302 }
3303
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003304 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3305 throws Exception {
3306 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003307 mContext.packageName = admin1.getPackageName();
3308 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003309 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3310 false/* because of completed device setup */);
Yanli Wan01c92552019-11-18 16:07:54 -08003311 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3312 false/* because of completed device setup */);
Victor Chang3e794af2016-03-04 13:48:17 +00003313 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3314 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3315 false/* because of non-split user */);
3316 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3317 false/* because of non-split user */);
3318 }
3319
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003320 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3321 throws Exception {
3322 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3323 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3324 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3325 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Yanli Wan01c92552019-11-18 16:07:54 -08003326 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3327 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003328 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3329 DevicePolicyManager.CODE_OK);
3330 assertCheckProvisioningPreCondition(
3331 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3332 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3333 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3334 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3335 }
3336
Nicolas Prevot45d29072017-01-18 16:11:19 +00003337 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3338 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003339 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003340 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3341
3342 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3343 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Yanli Wan01c92552019-11-18 16:07:54 -08003344 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3345 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003346 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003347 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003348
Eran Messeri6ad0e192019-12-01 20:01:21 +00003349 // COMP mode NOT is allowed.
Esteban Talavera01576862016-12-15 11:16:44 +00003350 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003351 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3352 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003353
Eran Messeri6ad0e192019-12-01 20:01:21 +00003354 // And other DPCs can NOT provision a managed profile.
Esteban Talavera01576862016-12-15 11:16:44 +00003355 assertCheckProvisioningPreCondition(
3356 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003357 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003358 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003359 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3360 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3361 }
Esteban Talavera01576862016-12-15 11:16:44 +00003362
Nicolas Prevot45d29072017-01-18 16:11:19 +00003363 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3364 throws Exception {
3365 setup_nonSplitUser_withDo_primaryUser();
3366 mContext.packageName = admin1.getPackageName();
3367 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003368 // The DO should not be allowed to initiate provisioning if the restriction is set by
3369 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003370 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003371 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3372 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3373 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003374 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003375 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3376 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3377 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3378 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003379 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003380 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3381
3382 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003383 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003384 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003385 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3387 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3388 }
3389
Eran Messeri6ad0e192019-12-01 20:01:21 +00003390 public void testCheckCannotSetProfileOwnerWithDeviceOwner() throws Exception {
3391 setup_nonSplitUser_withDo_primaryUser();
3392 final int managedProfileUserId = 18;
3393 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 1308);
3394
3395 final int userId = UserHandle.getUserId(managedProfileAdminUid);
3396 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
3397 UserHandle.USER_SYSTEM);
3398 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3399 setUpPackageManagerForFakeAdmin(admin1, managedProfileAdminUid, admin1);
3400 dpm.setActiveAdmin(admin1, false, userId);
3401 assertFalse(dpm.setProfileOwner(admin1, null, userId));
3402 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3403 }
3404
3405 public void testCheckProvisioningPreCondition_nonSplitUser_attemptingComp() throws Exception {
Nicolas Prevot45d29072017-01-18 16:11:19 +00003406 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3407 mContext.packageName = admin1.getPackageName();
3408 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3409
3410 // We can delete the managed profile to create a new one, so provisioning is allowed.
3411 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003412 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3413 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003414 assertCheckProvisioningPreCondition(
3415 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3416 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003417 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3418 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003419 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3420 }
3421
3422 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3423 throws Exception {
3424 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3425 mContext.packageName = admin1.getPackageName();
3426 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003427 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003428 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3429 eq(UserHandle.SYSTEM)))
3430 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003431 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003432 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3433 eq(UserHandle.SYSTEM)))
3434 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003435
3436 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003437 assertCheckProvisioningPreCondition(
3438 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3439 DpmMockContext.ANOTHER_PACKAGE_NAME,
3440 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3441 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3442 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003443
3444 // But the device owner can still do it because it has set the restriction itself.
3445 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003446 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3447 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003448 }
3449
3450 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003451 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003452 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003453 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3454 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003455 .thenReturn(false);
3456 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3457
3458 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003459 }
Victor Chang3e794af2016-03-04 13:48:17 +00003460
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003461 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3462 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003463 mContext.packageName = admin1.getPackageName();
3464 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003465 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003466 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003467 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3468 false /* because canAddMoreManagedProfiles returns false */);
3469 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3470 true);
3471 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3472 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003473 }
3474
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003475 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3476 throws Exception {
3477 setup_splitUser_firstBoot_systemUser();
3478 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3479 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3480 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003481 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3482 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003483 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003484 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003485 assertCheckProvisioningPreCondition(
3486 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3487 DevicePolicyManager.CODE_OK);
3488 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3489 DevicePolicyManager.CODE_SYSTEM_USER);
3490 }
3491
Esteban Talavera01576862016-12-15 11:16:44 +00003492 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003493 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003494 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003495 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3496 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003497 .thenReturn(false);
3498 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3499
3500 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003501 }
Victor Chang3e794af2016-03-04 13:48:17 +00003502
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003503 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3504 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003505 mContext.packageName = admin1.getPackageName();
3506 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003507 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3508 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003509 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3510 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003511 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3512 false /* because canAddMoreManagedProfiles returns false */);
3513 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3514 true/* it's undefined behavior. Can be changed into false in the future */);
3515 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3516 false/* because calling uid is system user */);
3517 }
3518
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003519 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3520 throws Exception {
3521 setup_splitUser_afterDeviceSetup_systemUser();
3522 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3523 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3524 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003525 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3526 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003527 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003528 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003529 assertCheckProvisioningPreCondition(
3530 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3531 DevicePolicyManager.CODE_OK);
3532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3533 DevicePolicyManager.CODE_SYSTEM_USER);
3534 }
3535
Esteban Talavera01576862016-12-15 11:16:44 +00003536 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003537 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003538 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003539 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3540 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003541 true)).thenReturn(true);
3542 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3543
3544 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003545 }
Victor Chang3e794af2016-03-04 13:48:17 +00003546
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003547 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3548 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003549 mContext.packageName = admin1.getPackageName();
3550 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003551 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003552 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003553 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3554 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3555 true);
3556 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003557 }
3558
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003559 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003560 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003561 setup_splitUser_firstBoot_primaryUser();
3562 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3563 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3564 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003565 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3566 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003567 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3568 DevicePolicyManager.CODE_OK);
3569 assertCheckProvisioningPreCondition(
3570 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3571 DevicePolicyManager.CODE_OK);
3572 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3573 DevicePolicyManager.CODE_OK);
3574 }
3575
Esteban Talavera01576862016-12-15 11:16:44 +00003576 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003577 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003578 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003579 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3580 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003581 true)).thenReturn(true);
3582 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3583
3584 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003585 }
Victor Chang3e794af2016-03-04 13:48:17 +00003586
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003587 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3588 throws Exception {
3589 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003590 mContext.packageName = admin1.getPackageName();
3591 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003592 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3593 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003594 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3595 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003596 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3597 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3598 true/* it's undefined behavior. Can be changed into false in the future */);
3599 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3600 false/* because user setup completed */);
3601 }
3602
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003603 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003604 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003605 setup_splitUser_afterDeviceSetup_primaryUser();
3606 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3607 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3608 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003609 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3610 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003611 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3612 DevicePolicyManager.CODE_OK);
3613 assertCheckProvisioningPreCondition(
3614 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3615 DevicePolicyManager.CODE_OK);
3616 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3617 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3618 }
3619
Esteban Talavera01576862016-12-15 11:16:44 +00003620 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003621 setDeviceOwner();
3622
Pavel Grafov75c0a892017-05-18 17:28:27 +01003623 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003624 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003625 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3626 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003627 .thenReturn(false);
3628 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3629
3630 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003631 }
Victor Chang3e794af2016-03-04 13:48:17 +00003632
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003633 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3634 throws Exception {
3635 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003636 mContext.packageName = admin1.getPackageName();
3637 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003638 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3639 false /* can't provision managed profile on system user */);
3640 }
3641
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003642 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003643 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003644 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3645 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3646 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3647 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3648 }
3649
3650 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003651 setDeviceOwner();
3652
Pavel Grafov75c0a892017-05-18 17:28:27 +01003653 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003654 .thenReturn(true);
Eran Messeri957d31d2020-01-16 10:21:26 +00003655 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
Eran Messeri6ad0e192019-12-01 20:01:21 +00003656 when(getServices().userManager.getProfileParent(DpmMockContext.CALLER_USER_HANDLE))
3657 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003658 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003659 true)).thenReturn(true);
3660 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3661
Eran Messeri957d31d2020-01-16 10:21:26 +00003662 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003663 }
Victor Chang3e794af2016-03-04 13:48:17 +00003664
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003665 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3666 throws Exception {
3667 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003668 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3669 mContext.packageName = admin1.getPackageName();
Eran Messeri6ad0e192019-12-01 20:01:21 +00003670 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003671 }
3672
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003673 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003674 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003675 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3676 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003677
Eran Messeri6ad0e192019-12-01 20:01:21 +00003678 // COMP mode is NOT allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003679 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003680 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003681 }
3682
3683 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003684 setDeviceOwner();
3685
Pavel Grafov75c0a892017-05-18 17:28:27 +01003686 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003687 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003688 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3689 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003690 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3691 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003692 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003693 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003694 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003695 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003696 true)).thenReturn(true);
3697 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3698
3699 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003700 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003701
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003702 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3703 throws Exception {
3704 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003705 mContext.packageName = admin1.getPackageName();
3706 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003707 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3708 }
3709
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003710 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3711 throws Exception {
3712 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3713 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3714 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3715 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3716 }
3717
3718 public void testCheckProvisioningPreCondition_permission() {
3719 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003720 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3721 () -> dpm.checkProvisioningPreCondition(
3722 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003723 }
3724
Victor Chang3577ed22016-08-25 18:49:26 +01003725 public void testForceUpdateUserSetupComplete_permission() {
3726 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003727 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3728 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003729 }
3730
3731 public void testForceUpdateUserSetupComplete_systemUser() {
3732 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3733 // GIVEN calling from user 20
3734 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003735 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3736 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003737 }
3738
3739 public void testForceUpdateUserSetupComplete_userbuild() {
3740 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3741 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3742
3743 final int userId = UserHandle.USER_SYSTEM;
3744 // GIVEN userComplete is false in SettingsProvider
3745 setUserSetupCompleteForUser(false, userId);
3746
3747 // GIVEN userComplete is true in DPM
3748 DevicePolicyManagerService.DevicePolicyData userData =
3749 new DevicePolicyManagerService.DevicePolicyData(userId);
3750 userData.mUserSetupComplete = true;
3751 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3752
3753 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003754 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003755
3756 assertTrue(dpms.hasUserSetupCompleted());
3757
3758 dpm.forceUpdateUserSetupComplete();
3759
3760 // THEN the state in dpms is not changed
3761 assertTrue(dpms.hasUserSetupCompleted());
3762 }
3763
3764 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3765 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3766 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3767
3768 final int userId = UserHandle.USER_SYSTEM;
3769 // GIVEN userComplete is false in SettingsProvider
3770 setUserSetupCompleteForUser(false, userId);
3771
3772 // GIVEN userComplete is true in DPM
3773 DevicePolicyManagerService.DevicePolicyData userData =
3774 new DevicePolicyManagerService.DevicePolicyData(userId);
3775 userData.mUserSetupComplete = true;
3776 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3777
3778 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003779 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003780
3781 assertTrue(dpms.hasUserSetupCompleted());
3782
3783 dpm.forceUpdateUserSetupComplete();
3784
3785 // THEN the state in dpms is not changed
3786 assertFalse(dpms.hasUserSetupCompleted());
3787 }
3788
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003789 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003790 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003791 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003792
3793 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3794 runAsCaller(mAdmin1Context, dpms, dpm -> {
3795 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3796 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003797 }
3798
3799 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3800 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3801 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003802
3803 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3804 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003805 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003806 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3807 .thenReturn(true);
3808
3809 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003810 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003811
3812 // Enabling logging should not change the timestamp.
3813 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003814 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003815 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003816 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003817 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003818 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003819
3820 // Retrieving the logs should update the timestamp.
3821 final long beforeRetrieval = System.currentTimeMillis();
3822 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003823 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003824 final long afterRetrieval = System.currentTimeMillis();
3825 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3826 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3827
3828 // Retrieving the pre-boot logs should update the timestamp.
3829 Thread.sleep(2);
3830 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003831 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003832 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3833
3834 // Checking the timestamp again should not change it.
3835 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003836 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003837
3838 // Retrieving the logs again should update the timestamp.
3839 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003840 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003841 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3842
3843 // Disabling logging should not change the timestamp.
3844 Thread.sleep(2);
3845 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003846 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003847
3848 // Restarting the DPMS should not lose the timestamp.
3849 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003850 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003851
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003852 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3853 mContext.binder.callingUid = 1234567;
3854 mContext.callerPermissions.add(permission.MANAGE_USERS);
3855 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3856 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3857
3858 // System can retrieve the timestamp.
3859 mContext.binder.clearCallingIdentity();
3860 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3861
3862 // Removing the device owner should clear the timestamp.
3863 clearDeviceOwner();
3864 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003865 }
3866
Alex Johnston57ec8092020-02-11 12:43:21 +00003867 public void testSetConfiguredNetworksLockdownStateWithDO() throws Exception {
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003868 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3869 setupDeviceOwner();
Alex Johnston57ec8092020-02-11 12:43:21 +00003870 dpm.setConfiguredNetworksLockdownState(admin1, true);
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003871 verify(getServices().settings).settingsGlobalPutInt(
3872 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3873
Alex Johnston57ec8092020-02-11 12:43:21 +00003874 dpm.setConfiguredNetworksLockdownState(admin1, false);
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003875 verify(getServices().settings).settingsGlobalPutInt(
3876 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3877 }
3878
Alex Johnston57ec8092020-02-11 12:43:21 +00003879 public void testSetConfiguredNetworksLockdownStateWithPO() throws Exception {
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003880 setupProfileOwner();
3881 assertExpectException(SecurityException.class, null,
Alex Johnston57ec8092020-02-11 12:43:21 +00003882 () -> dpm.setConfiguredNetworksLockdownState(admin1, false));
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003883 verify(getServices().settings, never()).settingsGlobalPutInt(
3884 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3885 }
3886
Alex Johnston57ec8092020-02-11 12:43:21 +00003887 public void testSetConfiguredNetworksLockdownStateWithPOOfOrganizationOwnedDevice()
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003888 throws Exception {
3889 setupProfileOwner();
3890 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Alex Johnston57ec8092020-02-11 12:43:21 +00003891 dpm.setConfiguredNetworksLockdownState(admin1, true);
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003892 verify(getServices().settings).settingsGlobalPutInt(
3893 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3894
Alex Johnston57ec8092020-02-11 12:43:21 +00003895 dpm.setConfiguredNetworksLockdownState(admin1, false);
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003896 verify(getServices().settings).settingsGlobalPutInt(
3897 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3898 }
3899
yuemingw0de748d2017-11-15 19:22:27 +00003900 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3901 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3902 setupDeviceOwner();
3903 assertExpectException(SecurityException.class, null, () ->
3904 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3905 }
3906
yuemingwc0281f12018-03-28 15:58:49 +01003907 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003908 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3909 setupDeviceOwner();
3910 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003911 verify(getServices().settings).settingsSystemPutStringForUser(
3912 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3913 }
3914
3915 public void testSetSystemSettingWithPO() throws Exception {
3916 setupProfileOwner();
3917 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3918 verify(getServices().settings).settingsSystemPutStringForUser(
3919 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003920 }
3921
Alex Johnston2e245292020-03-09 13:18:07 +00003922 public void testSetAutoTimeEnabledModifiesSetting() throws Exception {
Alex Johnston8c503382019-11-19 11:12:15 +00003923 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3924 setupDeviceOwner();
Alex Johnston2e245292020-03-09 13:18:07 +00003925 dpm.setAutoTimeEnabled(admin1, true);
Alex Johnston8c503382019-11-19 11:12:15 +00003926 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3927
Alex Johnston2e245292020-03-09 13:18:07 +00003928 dpm.setAutoTimeEnabled(admin1, false);
Alex Johnston8c503382019-11-19 11:12:15 +00003929 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3930 }
3931
Alex Johnston2e245292020-03-09 13:18:07 +00003932 public void testSetAutoTimeEnabledWithPOOnUser0() throws Exception {
Alex Johnston8c503382019-11-19 11:12:15 +00003933 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3934 setupProfileOwnerOnUser0();
Alex Johnston2e245292020-03-09 13:18:07 +00003935 dpm.setAutoTimeEnabled(admin1, true);
Alex Johnston8c503382019-11-19 11:12:15 +00003936 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3937
Alex Johnston2e245292020-03-09 13:18:07 +00003938 dpm.setAutoTimeEnabled(admin1, false);
Alex Johnston8c503382019-11-19 11:12:15 +00003939 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3940 }
3941
Alex Johnston2e245292020-03-09 13:18:07 +00003942 public void testSetAutoTimeEnabledFailWithPONotOnUser0() throws Exception {
Alex Johnston8c503382019-11-19 11:12:15 +00003943 setupProfileOwner();
Alex Johnston2e245292020-03-09 13:18:07 +00003944 assertExpectException(SecurityException.class, null,
3945 () -> dpm.setAutoTimeEnabled(admin1, false));
Alex Johnston8c503382019-11-19 11:12:15 +00003946 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3947 }
3948
Alex Johnston2e245292020-03-09 13:18:07 +00003949 public void testSetAutoTimeEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
Alex Johnston8c503382019-11-19 11:12:15 +00003950 setupProfileOwner();
3951 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3952
Alex Johnston2e245292020-03-09 13:18:07 +00003953 dpm.setAutoTimeEnabled(admin1, true);
Alex Johnston8c503382019-11-19 11:12:15 +00003954 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3955
Alex Johnston2e245292020-03-09 13:18:07 +00003956 dpm.setAutoTimeEnabled(admin1, false);
Alex Johnston8c503382019-11-19 11:12:15 +00003957 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3958 }
3959
Alex Johnston2e245292020-03-09 13:18:07 +00003960 public void testSetAutoTimeZoneEnabledModifiesSetting() throws Exception {
Alex Johnstona44d7292019-12-12 15:34:35 +00003961 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3962 setupDeviceOwner();
Alex Johnston2e245292020-03-09 13:18:07 +00003963 dpm.setAutoTimeZoneEnabled(admin1, true);
Alex Johnstona44d7292019-12-12 15:34:35 +00003964 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3965
Alex Johnston2e245292020-03-09 13:18:07 +00003966 dpm.setAutoTimeZoneEnabled(admin1, false);
Alex Johnstona44d7292019-12-12 15:34:35 +00003967 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3968 }
3969
Alex Johnston2e245292020-03-09 13:18:07 +00003970 public void testSetAutoTimeZoneEnabledWithPOOnUser0() throws Exception {
Alex Johnstona44d7292019-12-12 15:34:35 +00003971 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3972 setupProfileOwnerOnUser0();
Alex Johnston2e245292020-03-09 13:18:07 +00003973 dpm.setAutoTimeZoneEnabled(admin1, true);
Alex Johnstona44d7292019-12-12 15:34:35 +00003974 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3975
Alex Johnston2e245292020-03-09 13:18:07 +00003976 dpm.setAutoTimeZoneEnabled(admin1, false);
Alex Johnstona44d7292019-12-12 15:34:35 +00003977 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3978 }
3979
Alex Johnston2e245292020-03-09 13:18:07 +00003980 public void testSetAutoTimeZoneEnabledFailWithPONotOnUser0() throws Exception {
Alex Johnstona44d7292019-12-12 15:34:35 +00003981 setupProfileOwner();
3982 assertExpectException(SecurityException.class, null,
Alex Johnston2e245292020-03-09 13:18:07 +00003983 () -> dpm.setAutoTimeZoneEnabled(admin1, false));
Alex Johnstona44d7292019-12-12 15:34:35 +00003984 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
3985 0);
3986 }
3987
Alex Johnston2e245292020-03-09 13:18:07 +00003988 public void testSetAutoTimeZoneEnabledWithPOOfOrganizationOwnedDevice() throws Exception {
Alex Johnstona44d7292019-12-12 15:34:35 +00003989 setupProfileOwner();
3990 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3991
Alex Johnston2e245292020-03-09 13:18:07 +00003992 dpm.setAutoTimeZoneEnabled(admin1, true);
Alex Johnstona44d7292019-12-12 15:34:35 +00003993 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3994
Alex Johnston2e245292020-03-09 13:18:07 +00003995 dpm.setAutoTimeZoneEnabled(admin1, false);
Alex Johnstona44d7292019-12-12 15:34:35 +00003996 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3997 }
3998
Eran Messeria1015c82019-12-18 15:27:04 +00003999 public void testIsOrganizationOwnedDevice() throws Exception {
Eran Messeria1015c82019-12-18 15:27:04 +00004000 // Set up the user manager to return correct user info
Rubin Xu1480ce72020-02-05 11:38:08 +00004001 addManagedProfile(admin1, DpmMockContext.CALLER_UID, admin1);
Eran Messeria1015c82019-12-18 15:27:04 +00004002
Eran Messeri41c2aed2020-01-13 15:10:12 +00004003 // Any caller should be able to call this method.
Eran Messeria1015c82019-12-18 15:27:04 +00004004 assertFalse(dpm.isOrganizationOwnedDeviceWithManagedProfile());
4005 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
4006 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
4007
4008 // A random caller from another user should also be able to get the right result.
4009 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
4010 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
4011 }
4012
yuemingwe43cdf72017-10-12 16:52:11 +01004013 public void testSetTime() throws Exception {
4014 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4015 setupDeviceOwner();
4016 dpm.setTime(admin1, 0);
Neil Fullerce509622020-03-09 14:19:48 +00004017 verify(getServices().alarmManager).setTime(0);
yuemingwe43cdf72017-10-12 16:52:11 +01004018 }
4019
4020 public void testSetTimeFailWithPO() throws Exception {
4021 setupProfileOwner();
4022 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
4023 }
4024
Alex Johnstone81f05c2019-12-19 12:06:24 +00004025 public void testSetTimeWithPOOfOrganizationOwnedDevice() throws Exception {
4026 setupProfileOwner();
4027 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
4028 dpm.setTime(admin1, 0);
Neil Fullerce509622020-03-09 14:19:48 +00004029 verify(getServices().alarmManager).setTime(0);
Alex Johnstone81f05c2019-12-19 12:06:24 +00004030 }
4031
yuemingwe43cdf72017-10-12 16:52:11 +01004032 public void testSetTimeWithAutoTimeOn() throws Exception {
4033 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4034 setupDeviceOwner();
4035 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
4036 .thenReturn(1);
4037 assertFalse(dpm.setTime(admin1, 0));
4038 }
4039
4040 public void testSetTimeZone() throws Exception {
4041 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4042 setupDeviceOwner();
4043 dpm.setTimeZone(admin1, "Asia/Shanghai");
Neil Fullerce509622020-03-09 14:19:48 +00004044 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
yuemingwe43cdf72017-10-12 16:52:11 +01004045 }
4046
4047 public void testSetTimeZoneFailWithPO() throws Exception {
4048 setupProfileOwner();
4049 assertExpectException(SecurityException.class, null,
4050 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
4051 }
4052
Alex Johnstone81f05c2019-12-19 12:06:24 +00004053 public void testSetTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
4054 setupProfileOwner();
4055 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
4056 dpm.setTimeZone(admin1, "Asia/Shanghai");
Neil Fullerce509622020-03-09 14:19:48 +00004057 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
Alex Johnstone81f05c2019-12-19 12:06:24 +00004058 }
4059
yuemingwe43cdf72017-10-12 16:52:11 +01004060 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
4061 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4062 setupDeviceOwner();
4063 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
4064 .thenReturn(1);
4065 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
4066 }
4067
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004068 public void testGetLastBugReportRequestTime() throws Exception {
4069 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4070 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004071
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004072 mContext.packageName = admin1.getPackageName();
4073 mContext.applicationInfo = new ApplicationInfo();
4074 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4075 .thenReturn(Color.WHITE);
4076 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4077 anyObject())).thenReturn(Color.WHITE);
4078
Esteban Talaverad36dd152016-12-15 08:51:45 +00004079 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4080 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00004082
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004083 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004084 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004085
4086 // Requesting a bug report should update the timestamp.
4087 final long beforeRequest = System.currentTimeMillis();
4088 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004089 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004090 final long afterRequest = System.currentTimeMillis();
4091 assertTrue(bugReportRequestTime >= beforeRequest);
4092 assertTrue(bugReportRequestTime <= afterRequest);
4093
4094 // Checking the timestamp again should not change it.
4095 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004096 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004097
4098 // Restarting the DPMS should not lose the timestamp.
4099 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004100 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004101
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004102 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4103 mContext.binder.callingUid = 1234567;
4104 mContext.callerPermissions.add(permission.MANAGE_USERS);
4105 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4106 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4107
4108 // System can retrieve the timestamp.
4109 mContext.binder.clearCallingIdentity();
4110 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4111
4112 // Removing the device owner should clear the timestamp.
4113 clearDeviceOwner();
4114 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004115 }
4116
4117 public void testGetLastNetworkLogRetrievalTime() throws Exception {
4118 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4119 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004120 mContext.packageName = admin1.getPackageName();
4121 mContext.applicationInfo = new ApplicationInfo();
4122 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4123 .thenReturn(Color.WHITE);
4124 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4125 anyObject())).thenReturn(Color.WHITE);
4126
4127 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4128 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004129 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01004130 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004131 .thenReturn(true);
4132
4133 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004134 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004135
4136 // Attempting to retrieve logs without enabling logging should not change the timestamp.
4137 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004138 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004139
4140 // Enabling logging should not change the timestamp.
4141 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004142 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004143
4144 // Retrieving the logs should update the timestamp.
4145 final long beforeRetrieval = System.currentTimeMillis();
4146 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004147 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004148 final long afterRetrieval = System.currentTimeMillis();
4149 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
4150 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
4151
4152 // Checking the timestamp again should not change it.
4153 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004154 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004155
4156 // Retrieving the logs again should update the timestamp.
4157 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004158 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004159 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
4160
4161 // Disabling logging should not change the timestamp.
4162 Thread.sleep(2);
4163 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004164 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004165
4166 // Restarting the DPMS should not lose the timestamp.
4167 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004168 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4169
4170 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4171 mContext.binder.callingUid = 1234567;
4172 mContext.callerPermissions.add(permission.MANAGE_USERS);
4173 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4174 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4175
4176 // System can retrieve the timestamp.
4177 mContext.binder.clearCallingIdentity();
4178 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4179
4180 // Removing the device owner should clear the timestamp.
4181 clearDeviceOwner();
4182 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004183 }
4184
Tony Mak2f26b792016-11-28 17:54:51 +00004185 public void testGetBindDeviceAdminTargetUsers() throws Exception {
4186 // Setup device owner.
4187 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4188 setupDeviceOwner();
4189
4190 // Only device owner is setup, the result list should be empty.
4191 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4192 MoreAsserts.assertEmpty(targetUsers);
4193
Tony Mak2f26b792016-11-28 17:54:51 +00004194 // Add a secondary user, it should never talk with.
4195 final int ANOTHER_USER_ID = 36;
Alex Johnston755e3772019-11-29 03:27:22 +00004196 getServices().addUser(ANOTHER_USER_ID, 0, UserManager.USER_TYPE_FULL_SECONDARY);
Tony Mak2f26b792016-11-28 17:54:51 +00004197
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004198 // Since the managed profile is not affiliated, they should not be allowed to talk to each
4199 // other.
4200 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4201 MoreAsserts.assertEmpty(targetUsers);
4202
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004203 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01004204 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004205 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4206 dpm.setAffiliationIds(admin1, userAffiliationIds);
4207
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004208 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01004209 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004210
4211 // Since the managed profile is not affiliated any more, they should not be allowed to talk
4212 // to each other.
4213 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4214 MoreAsserts.assertEmpty(targetUsers);
4215
4216 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4217 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4218 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00004219 }
4220
Jason Parks3c13b642017-11-28 15:39:43 -06004221 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01004222 verifyLockTaskState(userId, new String[0],
4223 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06004224 }
4225
4226 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
4227 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004228 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06004229 }
4230
4231 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
4232 int flags) throws Exception {
4233 mContext.binder.callingUid = uid;
4234 dpm.setLockTaskPackages(who, packages);
4235 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
4236 for (String p : packages) {
4237 assertTrue(dpm.isLockTaskPermitted(p));
4238 }
4239 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
4240 // Test to see if set lock task features can be set
4241 dpm.setLockTaskFeatures(who, flags);
4242 verifyLockTaskState(userId, packages, flags);
4243 }
4244
4245 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
4246 int flags) throws Exception {
4247 mContext.binder.callingUid = uid;
4248 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4249 () -> dpm.setLockTaskPackages(who, packages));
4250 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4251 () -> dpm.getLockTaskPackages(who));
4252 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
4253 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4254 () -> dpm.setLockTaskFeatures(who, flags));
4255 }
4256
Jason Parks3c13b642017-11-28 15:39:43 -06004257 public void testLockTaskPolicyForProfileOwner() throws Exception {
4258 // Setup a PO
4259 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4260 setAsProfileOwner(admin1);
4261 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
4262
4263 final String[] poPackages = {"poPackage1", "poPackage2"};
4264 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004265 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4266 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004267 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
4268 poPackages, poFlags);
4269
4270 // Set up a managed profile managed by different package (package name shouldn't matter)
4271 final int MANAGED_PROFILE_USER_ID = 15;
4272 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
4273 final ComponentName adminDifferentPackage =
4274 new ComponentName("another.package", "whatever.class");
4275 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
4276 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
4277
4278 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
4279 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4280 final String[] mpoPackages = {"poPackage1", "poPackage2"};
4281 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004282 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4283 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004284 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00004285 }
4286
Benjamin Franzcaffa772018-02-05 16:36:10 +00004287 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
4288 // Setup a device owner.
4289 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4290 setupDeviceOwner();
4291 // Lock task policy is updated when loading user data.
4292 verifyLockTaskState(UserHandle.USER_SYSTEM);
4293
4294 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4295 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4296 assertExpectException(IllegalArgumentException.class,
4297 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4298 () -> dpm.setLockTaskFeatures(admin1, flags));
4299 }
4300
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004301 public void testSecondaryLockscreen_profileOwner() throws Exception {
4302 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4303
4304 // Initial state is disabled.
Yvonne Jiang8345da32020-03-19 15:01:16 -07004305 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4306 DpmMockContext.CALLER_USER_HANDLE)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004307
4308 // Profile owner can set enabled state.
4309 setAsProfileOwner(admin1);
Yvonne Jiang70a62372020-03-31 16:51:17 -07004310 when(mServiceContext.resources
4311 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4312 .thenReturn(admin1.flattenToString());
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004313 dpm.setSecondaryLockscreenEnabled(admin1, true);
Yvonne Jiang8345da32020-03-19 15:01:16 -07004314 assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4315 DpmMockContext.CALLER_USER_HANDLE)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004316
4317 // Managed profile managed by different package is unaffiliated - cannot set enabled.
4318 final int managedProfileUserId = 15;
4319 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 20456);
4320 final ComponentName adminDifferentPackage =
4321 new ComponentName("another.package", "whatever.class");
4322 addManagedProfile(adminDifferentPackage, managedProfileAdminUid, admin2);
4323 mContext.binder.callingUid = managedProfileAdminUid;
4324 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4325 () -> dpm.setSecondaryLockscreenEnabled(adminDifferentPackage, false));
4326 }
4327
4328 public void testSecondaryLockscreen_deviceOwner() throws Exception {
4329 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4330
4331 // Initial state is disabled.
Yvonne Jiang8345da32020-03-19 15:01:16 -07004332 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004333
4334 // Device owners can set enabled state.
4335 setupDeviceOwner();
Yvonne Jiang70a62372020-03-31 16:51:17 -07004336 when(mServiceContext.resources
4337 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4338 .thenReturn(admin1.flattenToString());
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004339 dpm.setSecondaryLockscreenEnabled(admin1, true);
Yvonne Jiang8345da32020-03-19 15:01:16 -07004340 assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.of(UserHandle.USER_SYSTEM)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004341 }
4342
4343 public void testSecondaryLockscreen_nonOwner() throws Exception {
4344 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4345
4346 // Initial state is disabled.
Yvonne Jiang8345da32020-03-19 15:01:16 -07004347 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4348 DpmMockContext.CALLER_USER_HANDLE)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004349
4350 // Non-DO/PO cannot set enabled state.
Yvonne Jiang70a62372020-03-31 16:51:17 -07004351 when(mServiceContext.resources
4352 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4353 .thenReturn(admin1.flattenToString());
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004354 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4355 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
Yvonne Jiang8345da32020-03-19 15:01:16 -07004356 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4357 DpmMockContext.CALLER_USER_HANDLE)));
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004358 }
4359
Yvonne Jiang70a62372020-03-31 16:51:17 -07004360 public void testSecondaryLockscreen_nonSupervisionApp() throws Exception {
4361 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4362
4363 // Initial state is disabled.
4364 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4365 DpmMockContext.CALLER_USER_HANDLE)));
4366
4367 // Caller is Profile Owner, but no supervision app is configured.
4368 setAsProfileOwner(admin1);
4369 assertExpectException(SecurityException.class, "no default supervision component defined",
4370 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
4371 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4372 DpmMockContext.CALLER_USER_HANDLE)));
4373
4374 // Caller is Profile Owner, but is not the default configured supervision app.
4375 when(mServiceContext.resources
4376 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
4377 .thenReturn(admin2.flattenToString());
4378 assertExpectException(SecurityException.class, "is not the default supervision component",
4379 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
4380 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.of(
4381 DpmMockContext.CALLER_USER_HANDLE)));
4382 }
4383
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01004384 public void testIsDeviceManaged() throws Exception {
4385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4386 setupDeviceOwner();
4387
4388 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
4389 // find out that the device has a device owner.
4390 assertTrue(dpm.isDeviceManaged());
4391 mContext.binder.callingUid = 1234567;
4392 mContext.callerPermissions.add(permission.MANAGE_USERS);
4393 assertTrue(dpm.isDeviceManaged());
4394 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4395 mContext.binder.clearCallingIdentity();
4396 assertTrue(dpm.isDeviceManaged());
4397
4398 clearDeviceOwner();
4399
4400 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4401 // not have a device owner.
4402 mContext.binder.callingUid = 1234567;
4403 mContext.callerPermissions.add(permission.MANAGE_USERS);
4404 assertFalse(dpm.isDeviceManaged());
4405 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4406 mContext.binder.clearCallingIdentity();
4407 assertFalse(dpm.isDeviceManaged());
4408 }
4409
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004410 public void testDeviceOwnerOrganizationName() throws Exception {
4411 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4412 setupDeviceOwner();
4413
4414 dpm.setOrganizationName(admin1, "organization");
4415
4416 // Device owner can retrieve organization managing the device.
4417 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4418
4419 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4420 mContext.binder.callingUid = 1234567;
4421 mContext.callerPermissions.add(permission.MANAGE_USERS);
4422 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4423 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4424
4425 // System can retrieve organization managing the device.
4426 mContext.binder.clearCallingIdentity();
4427 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4428
4429 // Removing the device owner clears the organization managing the device.
4430 clearDeviceOwner();
4431 assertNull(dpm.getDeviceOwnerOrganizationName());
4432 }
4433
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004434 public void testWipeDataManagedProfile() throws Exception {
4435 final int MANAGED_PROFILE_USER_ID = 15;
4436 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4437 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4438 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4439
4440 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004441 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004442 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004443 // Get mock reason string since we throw an IAE with empty string input.
4444 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4445 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004446
4447 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004448 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004449 MANAGED_PROFILE_USER_ID);
4450 }
4451
4452 public void testWipeDataManagedProfileDisallowed() throws Exception {
4453 final int MANAGED_PROFILE_USER_ID = 15;
4454 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4455 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4456
4457 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004459 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4460
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004462 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4463 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4464 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004465 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4466 thenReturn("Just a test string.");
4467
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004468 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004469 // The PO is not allowed to remove the profile if the user restriction was set on the
4470 // profile by the system
4471 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4472 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004473 }
4474
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004475 public void testWipeDataDeviceOwner() throws Exception {
4476 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004477 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004478 UserManager.DISALLOW_FACTORY_RESET,
4479 UserHandle.SYSTEM))
4480 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004481 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4482 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004483
4484 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004485 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004486 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4487 /*wipeEuicc=*/ eq(false));
4488 }
4489
4490 public void testWipeEuiccDataEnabled() throws Exception {
4491 setDeviceOwner();
4492 when(getServices().userManager.getUserRestrictionSource(
4493 UserManager.DISALLOW_FACTORY_RESET,
4494 UserHandle.SYSTEM))
4495 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004496 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4497 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004498
4499 dpm.wipeData(WIPE_EUICC);
4500 verify(getServices().recoverySystem).rebootWipeUserData(
4501 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4502 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004503 }
4504
4505 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4506 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004507 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004508 UserManager.DISALLOW_FACTORY_RESET,
4509 UserHandle.SYSTEM))
4510 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004511 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4512 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004513 // The DO is not allowed to wipe the device if the user restriction was set
4514 // by the system
4515 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4516 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004517 }
4518
4519 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4520 final int MANAGED_PROFILE_USER_ID = 15;
4521 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4522 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4523
4524 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004525 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004526 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4527
Pavel Grafov75c0a892017-05-18 17:28:27 +01004528 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004529 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4530 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4531 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4532
4533 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4534 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4535
4536 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4537 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4538 // Failed password attempts on the parent user are taken into account, as there isn't a
4539 // separate work challenge.
4540 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4541 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4542 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4543
4544 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4545 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004546 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004547 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004548 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004549 }
4550
4551 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4552 throws Exception {
4553 final int MANAGED_PROFILE_USER_ID = 15;
4554 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4555 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4556
4557 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004558 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004559 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4560
Pavel Grafov75c0a892017-05-18 17:28:27 +01004561 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004562 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4563 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4564 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4565
4566 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4567 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4568
4569 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4570 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4571 // Failed password attempts on the parent user are taken into account, as there isn't a
4572 // separate work challenge.
4573 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4574 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4575 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4576
4577 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4578 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004579 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004580 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004581 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004582 }
4583
4584 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4585 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004586 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004587 UserManager.DISALLOW_FACTORY_RESET,
4588 UserHandle.SYSTEM))
4589 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4590
4591 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4592
4593 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4594 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4595 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4596 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4597 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4598
4599 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4600 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004601 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004602 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4603 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004604 }
4605
4606 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4607 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004608 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004609 UserManager.DISALLOW_FACTORY_RESET,
4610 UserHandle.SYSTEM))
4611 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4612
4613 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4614
4615 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4616 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4617 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4618 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4619 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4620
4621 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004622 verifyZeroInteractions(getServices().recoverySystem);
4623 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004624 .removeUserEvenWhenDisallowed(anyInt());
4625 }
4626
Pavel Grafova5b15b22020-02-03 16:06:20 +00004627 public void testMaximumFailedDevicePasswordAttemptsReachedOrgOwnedManagedProfile()
4628 throws Exception {
4629 final int MANAGED_PROFILE_USER_ID = 15;
4630 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4631 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4632
4633 // Even if the caller is the managed profile, the current user is the user 0
4634 when(getServices().iactivityManager.getCurrentUser())
4635 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4636
4637 configureProfileOwnerOfOrgOwnedDevice(admin1, MANAGED_PROFILE_USER_ID);
4638
4639 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4640 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4641
4642 assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(admin1));
4643 assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null));
4644
4645 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4646 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4647
4648 assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM));
4649 // Check that primary will be wiped as a result of failed primary user unlock attempts.
4650 assertEquals(UserHandle.USER_SYSTEM,
4651 dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM));
4652
4653 // Failed password attempts on the parent user are taken into account, as there isn't a
4654 // separate work challenge.
4655 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4656 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4657 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4658
4659 // For managed profile on an organization owned device, the whole device should be wiped.
4660 verify(getServices().recoverySystem).rebootWipeUserData(
4661 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4662 /*wipeEuicc=*/ eq(false));
4663 }
4664
4665 public void testMaximumFailedProfilePasswordAttemptsReachedOrgOwnedManagedProfile()
4666 throws Exception {
4667 final int MANAGED_PROFILE_USER_ID = 15;
4668 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4669 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4670
4671 // Even if the caller is the managed profile, the current user is the user 0
4672 when(getServices().iactivityManager.getCurrentUser())
4673 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4674
4675 doReturn(true).when(getServices().lockPatternUtils)
4676 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
4677
4678 // Configure separate challenge.
4679 configureProfileOwnerOfOrgOwnedDevice(admin1, MANAGED_PROFILE_USER_ID);
4680
4681 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4682 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4683
4684 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4685 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4686
4687 assertEquals(0, dpm.getMaximumFailedPasswordsForWipe(null, UserHandle.USER_SYSTEM));
4688 assertEquals(3, dpm.getMaximumFailedPasswordsForWipe(null, MANAGED_PROFILE_USER_ID));
4689 // Check that the policy is not affecting primary profile challenge.
4690 assertEquals(UserHandle.USER_NULL,
4691 dpm.getProfileWithMinimumFailedPasswordsForWipe(UserHandle.USER_SYSTEM));
4692 // Check that primary will be wiped as a result of failed profile unlock attempts.
4693 assertEquals(UserHandle.USER_SYSTEM,
4694 dpm.getProfileWithMinimumFailedPasswordsForWipe(MANAGED_PROFILE_USER_ID));
4695
4696 // Simulate three failed attempts at solving the separate challenge.
4697 dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
4698 dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
4699 dpm.reportFailedPasswordAttempt(MANAGED_PROFILE_USER_ID);
4700
4701 // For managed profile on an organization owned device, the whole device should be wiped.
4702 verify(getServices().recoverySystem).rebootWipeUserData(
4703 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4704 /*wipeEuicc=*/ eq(false));
4705 }
4706
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004707 public void testGetPermissionGrantState() throws Exception {
4708 final String permission = "some.permission";
4709 final String app1 = "com.example.app1";
4710 final String app2 = "com.example.app2";
4711
Pavel Grafov75c0a892017-05-18 17:28:27 +01004712 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004713 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004714 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004715 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004716 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004717 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4718 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004719 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004720 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004721 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004722 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004723 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004724 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4725
4726 // System can retrieve permission grant state.
4727 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004728 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004729 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4730 dpm.getPermissionGrantState(null, app1, permission));
4731 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4732 dpm.getPermissionGrantState(null, app2, permission));
4733
4734 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004735 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4736 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004737 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4738 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004739
4740 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004741 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4742 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004743 setAsProfileOwner(admin1);
4744 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4745 dpm.getPermissionGrantState(admin1, app1, permission));
4746 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4747 dpm.getPermissionGrantState(admin1, app2, permission));
4748 }
4749
Rubin Xuaab7a412016-12-30 21:13:29 +00004750 public void testResetPasswordWithToken() throws Exception {
4751 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4752 setupDeviceOwner();
4753 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004754 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4755 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4756
Rubin Xuaab7a412016-12-30 21:13:29 +00004757 // test adding a token
4758 final byte[] token = new byte[32];
4759 final long handle = 123456;
4760 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004761 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4762 nullable(EscrowTokenStateChangeCallback.class)))
4763 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004764 assertTrue(dpm.setResetPasswordToken(admin1, token));
4765
4766 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004767 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004768 .thenReturn(true);
4769 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4770
4771 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004772 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4773 eq(LockscreenCredential.createPassword(password)),
4774 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004775 eq(UserHandle.USER_SYSTEM)))
4776 .thenReturn(true);
4777 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4778
4779 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004780 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004781 .thenReturn(true);
4782 assertTrue(dpm.clearResetPasswordToken(admin1));
4783 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004784
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004785 public void testIsActivePasswordSufficient() throws Exception {
4786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4787 mContext.packageName = admin1.getPackageName();
4788 setupDeviceOwner();
4789
4790 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4791 dpm.setPasswordMinimumLength(admin1, 8);
4792 dpm.setPasswordMinimumLetters(admin1, 6);
4793 dpm.setPasswordMinimumLowerCase(admin1, 3);
4794 dpm.setPasswordMinimumUpperCase(admin1, 1);
4795 dpm.setPasswordMinimumNonLetter(admin1, 1);
4796 dpm.setPasswordMinimumNumeric(admin1, 1);
4797 dpm.setPasswordMinimumSymbols(admin1, 0);
4798
Rubin Xucc391c22018-01-02 20:37:35 +00004799 reset(mContext.spiedContext);
4800
Pavel Grafov6f334842019-08-06 14:37:06 +01004801 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004802
4803 setActivePasswordState(passwordMetricsNoSymbols);
4804 assertTrue(dpm.isActivePasswordSufficient());
4805
4806 initializeDpms();
4807 reset(mContext.spiedContext);
4808 assertTrue(dpm.isActivePasswordSufficient());
4809
4810 // This call simulates the user entering the password for the first time after a reboot.
4811 // This causes password metrics to be reloaded into memory. Until this happens,
4812 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4813 // even if the DPC changes password requirements so that the password no longer meets the
4814 // requirements. This is a known limitation of the current implementation of
4815 // isActivePasswordSufficient() - see b/34218769.
4816 setActivePasswordState(passwordMetricsNoSymbols);
4817 assertTrue(dpm.isActivePasswordSufficient());
4818
4819 dpm.setPasswordMinimumSymbols(admin1, 1);
4820 // This assertion would fail if we had not called setActivePasswordState() again after
4821 // initializeDpms() - see previous comment.
4822 assertFalse(dpm.isActivePasswordSufficient());
4823
4824 initializeDpms();
4825 reset(mContext.spiedContext);
4826 assertFalse(dpm.isActivePasswordSufficient());
4827
Pavel Grafov6f334842019-08-06 14:37:06 +01004828 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004829
4830 setActivePasswordState(passwordMetricsWithSymbols);
4831 assertTrue(dpm.isActivePasswordSufficient());
4832 }
4833
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004834 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4835 // If there is no lock screen, the password is considered empty no matter what, because
4836 // it provides no security.
4837 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4838
4839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4840 mContext.packageName = admin1.getPackageName();
4841 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004842 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4843 // When there is no lockscreen, user password metrics is always empty.
4844 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004845 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004846
4847 // If no password requirements are set, isActivePasswordSufficient should succeed.
4848 assertTrue(dpm.isActivePasswordSufficient());
4849
4850 // Now set some password quality requirements.
4851 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4852
4853 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004854 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004855 dpm.reportPasswordChanged(userHandle);
4856
4857 // No broadcast should be sent.
4858 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4859 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4860 MockUtils.checkUserHandle(userHandle));
4861
4862 // The active (nonexistent) password doesn't comply with the requirements.
4863 assertFalse(dpm.isActivePasswordSufficient());
4864 }
4865
Rubin Xude633f32020-04-02 16:37:32 +01004866 public void testIsPasswordSufficientAfterProfileUnification() throws Exception {
4867 final int managedProfileUserId = DpmMockContext.CALLER_USER_HANDLE;
4868 final int managedProfileAdminUid =
4869 UserHandle.getUid(managedProfileUserId, DpmMockContext.SYSTEM_UID);
4870 mContext.binder.callingUid = managedProfileAdminUid;
4871
4872 addManagedProfile(admin1, managedProfileAdminUid, admin1);
4873 doReturn(true).when(getServices().lockPatternUtils)
4874 .isSeparateProfileChallengeEnabled(managedProfileUserId);
4875
4876 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC);
4877 parentDpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC);
4878
4879 when(getServices().lockSettingsInternal.getUserPasswordMetrics(UserHandle.USER_SYSTEM))
4880 .thenReturn(computeForPassword("1234".getBytes()));
4881
4882 // Numeric password is compliant with current requirement (QUALITY_NUMERIC set explicitly
4883 // on the parent admin)
4884 assertTrue(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM,
4885 UserHandle.USER_NULL));
4886 // Numeric password is not compliant if profile is to be unified: the profile has a
4887 // QUALITY_ALPHABETIC policy on itself which will be enforced on the password after
4888 // unification.
4889 assertFalse(dpm.isPasswordSufficientAfterProfileUnification(UserHandle.USER_SYSTEM,
4890 managedProfileUserId));
4891 }
4892
Pavel Grafov75c0a892017-05-18 17:28:27 +01004893 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4894 throws Exception {
4895 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004896 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004897
Rubin Xu19854862019-08-15 16:37:23 +01004898 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4899 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004900 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004901
Rubin Xucc391c22018-01-02 20:37:35 +00004902 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4903 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004904 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004905 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4906 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004907 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004908 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4909 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004910 // userId, if the password checkpoint value changes.
4911 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4912 MockUtils.checkIntentAction(
4913 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4914 MockUtils.checkUserHandle(userHandle));
4915 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004916 MockUtils.checkIntentAction(
4917 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4918 MockUtils.checkUserHandle(userHandle));
4919
Pavel Grafov75c0a892017-05-18 17:28:27 +01004920 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4921 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004922 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004923
4924 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4925 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004926 MockUtils.checkUserHandle(userHandle),
4927 eq(null),
4928 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004929
4930 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4931 // let it finish with system uid, otherwise it will throw and crash.
4932 flushTasks();
4933
4934 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004935 }
4936
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004937 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4938 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4939 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4940 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4941 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4942 DpmMockContext.SYSTEM_UID);
4943 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4944 DpmMockContext.SYSTEM_UID);
4945
4946 // Set up a device owner.
4947 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004948 setupDeviceOwner();
4949
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004950 // First and second user set IMEs manually.
4951 mContext.binder.callingUid = firstUserSystemUid;
4952 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4953 mContext.binder.callingUid = secondUserSystemUid;
4954 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004955
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004956 // Device owner changes IME for first user.
4957 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004958 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004959 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004960 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004961 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004962 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004963 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004964 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4965 mContext.binder.callingUid = firstUserSystemUid;
4966 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4967 mContext.binder.callingUid = secondUserSystemUid;
4968 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004969
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004970 // Second user changes IME manually.
4971 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4972 mContext.binder.callingUid = firstUserSystemUid;
4973 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4974 mContext.binder.callingUid = secondUserSystemUid;
4975 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004976
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004977 // First user changes IME manually.
4978 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4979 mContext.binder.callingUid = firstUserSystemUid;
4980 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4981 mContext.binder.callingUid = secondUserSystemUid;
4982 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004983
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004984 // Device owner changes IME for first user again.
4985 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004986 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004987 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004988 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004989 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004990 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004991 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4992 mContext.binder.callingUid = firstUserSystemUid;
4993 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4994 mContext.binder.callingUid = secondUserSystemUid;
4995 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004996
4997 // Restarting the DPMS should not lose information.
4998 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004999 mContext.binder.callingUid = firstUserSystemUid;
5000 assertTrue(dpm.isCurrentInputMethodSetByOwner());
5001 mContext.binder.callingUid = secondUserSystemUid;
5002 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005003
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005004 // Device owner can find out whether it set the current IME itself.
5005 mContext.binder.callingUid = deviceOwnerUid;
5006 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005007
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005008 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005009 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005010 mContext.binder.callingUid = firstUserSystemUid;
5011 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5012 mContext.binder.callingUid = secondUserSystemUid;
5013 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005014 }
5015
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005016 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
5017 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
5018 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
5019 final int profileOwnerUid = DpmMockContext.CALLER_UID;
5020 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
5021 DpmMockContext.SYSTEM_UID);
5022 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5023 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005024
5025 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005026 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005027 setupProfileOwner();
5028
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005029 // First and second user set IMEs manually.
5030 mContext.binder.callingUid = firstUserSystemUid;
5031 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5032 mContext.binder.callingUid = secondUserSystemUid;
5033 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005034
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005035 // Profile owner changes IME for second user.
5036 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005037 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005038 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005039 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01005040 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005041 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005042 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005043 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
5044 mContext.binder.callingUid = firstUserSystemUid;
5045 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5046 mContext.binder.callingUid = secondUserSystemUid;
5047 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005048
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005049 // First user changes IME manually.
5050 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
5051 mContext.binder.callingUid = firstUserSystemUid;
5052 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5053 mContext.binder.callingUid = secondUserSystemUid;
5054 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005055
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005056 // Second user changes IME manually.
5057 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
5058 mContext.binder.callingUid = firstUserSystemUid;
5059 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5060 mContext.binder.callingUid = secondUserSystemUid;
5061 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005062
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005063 // Profile owner changes IME for second user again.
5064 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005065 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005066 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005067 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01005068 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005069 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005070 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
5071 mContext.binder.callingUid = firstUserSystemUid;
5072 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5073 mContext.binder.callingUid = secondUserSystemUid;
5074 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005075
5076 // Restarting the DPMS should not lose information.
5077 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005078 mContext.binder.callingUid = firstUserSystemUid;
5079 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5080 mContext.binder.callingUid = secondUserSystemUid;
5081 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005082
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005083 // Profile owner can find out whether it set the current IME itself.
5084 mContext.binder.callingUid = profileOwnerUid;
5085 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005086
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005087 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005088 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01005089 mContext.binder.callingUid = firstUserSystemUid;
5090 assertFalse(dpm.isCurrentInputMethodSetByOwner());
5091 mContext.binder.callingUid = secondUserSystemUid;
5092 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01005093 }
Rubin Xuaab7a412016-12-30 21:13:29 +00005094
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005095 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
5096 throws Exception {
5097 // Set up a device owner.
5098 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5099 setupDeviceOwner();
5100 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
5101 }
5102
5103 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
5104 throws Exception {
5105 // Set up a profile owner.
5106 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5107 setupProfileOwner();
5108 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
5109 }
5110
5111 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
5112 int adminUid) throws Exception {
5113 mContext.binder.callingUid = adminUid;
5114 final int userId = UserHandle.getUserId(adminUid);
5115
5116 final String packageName = "some.package";
5117 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
5118 admin1, Collections.singletonList(packageName)));
5119 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5120
5121 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5122 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
5123
5124 // Attempt to set to empty list (which means no listener is whitelisted)
5125 mContext.binder.callingUid = adminUid;
5126 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005127 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005128 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5129
5130 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5131 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
5132 }
5133
5134 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
5135 // Set up a managed profile
5136 final int MANAGED_PROFILE_USER_ID = 15;
5137 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5138 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5139 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5140
5141 final String permittedListener = "some.package";
5142 setupPackageInPackageManager(
5143 permittedListener,
5144 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5145 /*appId=*/ 12345, /*flags=*/ 0);
5146
5147 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
5148 admin1, Collections.singletonList(permittedListener)));
5149
Pavel Grafova1ea8d92017-05-25 21:55:24 +01005150 // isNotificationListenerServicePermitted should throw if not called from System.
5151 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5152 () -> dpms.isNotificationListenerServicePermitted(
5153 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005154
5155 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5156 assertTrue(dpms.isNotificationListenerServicePermitted(
5157 permittedListener, MANAGED_PROFILE_USER_ID));
5158 }
5159
5160 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
5161 throws Exception {
5162 // Set up a managed profile
5163 final int MANAGED_PROFILE_USER_ID = 15;
5164 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5165 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5166 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5167
5168 final String permittedListener = "permitted.package";
5169 int appId = 12345;
5170 setupPackageInPackageManager(
5171 permittedListener,
5172 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5173 appId, /*flags=*/ 0);
5174
5175 final String notPermittedListener = "not.permitted.package";
5176 setupPackageInPackageManager(
5177 notPermittedListener,
5178 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5179 ++appId, /*flags=*/ 0);
5180
5181 final String systemListener = "system.package";
5182 setupPackageInPackageManager(
5183 systemListener,
5184 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5185 ++appId, ApplicationInfo.FLAG_SYSTEM);
5186
5187 // By default all packages are allowed
5188 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5189
5190 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5191 assertTrue(dpms.isNotificationListenerServicePermitted(
5192 permittedListener, MANAGED_PROFILE_USER_ID));
5193 assertTrue(dpms.isNotificationListenerServicePermitted(
5194 notPermittedListener, MANAGED_PROFILE_USER_ID));
5195 assertTrue(dpms.isNotificationListenerServicePermitted(
5196 systemListener, MANAGED_PROFILE_USER_ID));
5197
5198 // Setting only one package in the whitelist
5199 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5200 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
5201 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005202 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005203 dpms.getPermittedCrossProfileNotificationListeners(admin1);
5204 assertEquals(1, permittedListeners.size());
5205 assertEquals(permittedListener, permittedListeners.get(0));
5206
5207 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5208 assertTrue(dpms.isNotificationListenerServicePermitted(
5209 permittedListener, MANAGED_PROFILE_USER_ID));
5210 assertFalse(dpms.isNotificationListenerServicePermitted(
5211 notPermittedListener, MANAGED_PROFILE_USER_ID));
5212 // System packages are always allowed (even if not in the whitelist)
5213 assertTrue(dpms.isNotificationListenerServicePermitted(
5214 systemListener, MANAGED_PROFILE_USER_ID));
5215
5216 // Setting an empty whitelist - only system listeners allowed
5217 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5218 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005219 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005220 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5221
5222 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5223 assertFalse(dpms.isNotificationListenerServicePermitted(
5224 permittedListener, MANAGED_PROFILE_USER_ID));
5225 assertFalse(dpms.isNotificationListenerServicePermitted(
5226 notPermittedListener, MANAGED_PROFILE_USER_ID));
5227 // System packages are always allowed (even if not in the whitelist)
5228 assertTrue(dpms.isNotificationListenerServicePermitted(
5229 systemListener, MANAGED_PROFILE_USER_ID));
5230
5231 // Setting a null whitelist - all listeners allowed
5232 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5233 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
5234 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5235
5236 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5237 assertTrue(dpms.isNotificationListenerServicePermitted(
5238 permittedListener, MANAGED_PROFILE_USER_ID));
5239 assertTrue(dpms.isNotificationListenerServicePermitted(
5240 notPermittedListener, MANAGED_PROFILE_USER_ID));
5241 assertTrue(dpms.isNotificationListenerServicePermitted(
5242 systemListener, MANAGED_PROFILE_USER_ID));
5243 }
5244
5245 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
5246 throws Exception {
5247 // Set up a managed profile
5248 final int MANAGED_PROFILE_USER_ID = 15;
5249 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5250 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5251 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5252
5253 final String nonSystemPackage = "non.system.package";
5254 int appId = 12345;
5255 setupPackageInPackageManager(
5256 nonSystemPackage,
5257 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5258 appId, /*flags=*/ 0);
5259
5260 final String systemListener = "system.package";
5261 setupPackageInPackageManager(
5262 systemListener,
5263 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5264 ++appId, ApplicationInfo.FLAG_SYSTEM);
5265
5266 // By default all packages are allowed (for all profiles)
5267 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5268
5269 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5270 assertTrue(dpms.isNotificationListenerServicePermitted(
5271 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5272 assertTrue(dpms.isNotificationListenerServicePermitted(
5273 systemListener, MANAGED_PROFILE_USER_ID));
5274 assertTrue(dpms.isNotificationListenerServicePermitted(
5275 nonSystemPackage, UserHandle.USER_SYSTEM));
5276 assertTrue(dpms.isNotificationListenerServicePermitted(
5277 systemListener, UserHandle.USER_SYSTEM));
5278
5279 // Setting an empty whitelist - only system listeners allowed in managed profile, but
5280 // all allowed in primary profile
5281 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5282 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005283 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005284 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5285
5286 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5287 assertFalse(dpms.isNotificationListenerServicePermitted(
5288 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5289 assertTrue(dpms.isNotificationListenerServicePermitted(
5290 systemListener, MANAGED_PROFILE_USER_ID));
5291 assertTrue(dpms.isNotificationListenerServicePermitted(
5292 nonSystemPackage, UserHandle.USER_SYSTEM));
5293 assertTrue(dpms.isNotificationListenerServicePermitted(
5294 systemListener, UserHandle.USER_SYSTEM));
5295 }
5296
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005297 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005298 mServiceContext.packageName = mRealTestContext.getPackageName();
5299 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5300 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005301 setDeviceOwner();
5302
Pavel Grafov75c0a892017-05-18 17:28:27 +01005303 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005304 }
5305
5306 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005307 mServiceContext.packageName = mRealTestContext.getPackageName();
5308 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5309 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005310 setAsProfileOwner(admin1);
5311
Pavel Grafov75c0a892017-05-18 17:28:27 +01005312 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
5313 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005314 }
5315
5316 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005317 mServiceContext.packageName = mRealTestContext.getPackageName();
5318 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5319 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005320 setAsProfileOwner(admin1);
5321
Pavel Grafov75c0a892017-05-18 17:28:27 +01005322 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
5323 caller.packageName = "com.example.delegate";
5324 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
5325 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005326
Pavel Grafov75c0a892017-05-18 17:28:27 +01005327 // Make caller a delegated cert installer.
5328 runAsCaller(mAdmin1Context, dpms,
5329 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00005330
5331 verifyCanGetOwnerInstalledCaCerts(null, caller);
5332 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005333 }
5334
Rubin Xucc391c22018-01-02 20:37:35 +00005335 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005336 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5337 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005338 Bundle restriction = new Bundle();
5339 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5340
5341 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5342 RestrictionsListener listener = new RestrictionsListener(mContext);
5343 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
5344 new Bundle());
5345 verifyDataSharingChangedBroadcast();
5346 }
5347
5348 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005349 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5350 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005351 Bundle restriction = new Bundle();
5352 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5353
5354 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5355 RestrictionsListener listener = new RestrictionsListener(mContext);
5356 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5357 restriction);
5358 verifyDataSharingChangedBroadcast();
5359 }
5360
5361 public void testDisallowSharingIntoProfileUnchanged() {
5362 RestrictionsListener listener = new RestrictionsListener(mContext);
5363 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5364 new Bundle());
5365 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
5366 }
5367
5368 private void verifyDataSharingChangedBroadcast() {
5369 Intent expectedIntent = new Intent(
5370 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
5371 expectedIntent.setPackage("com.android.managedprovisioning");
5372 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
5373 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
5374 MockUtils.checkIntent(expectedIntent),
5375 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
5376 }
5377
yuemingwe3d9c092018-01-11 12:11:44 +00005378 public void testOverrideApnAPIsFailWithPO() throws Exception {
5379 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00005380 ApnSetting apn = (new ApnSetting.Builder())
5381 .setApnName("test")
5382 .setEntryName("test")
5383 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
5384 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00005385 assertExpectException(SecurityException.class, null, () ->
5386 dpm.addOverrideApn(admin1, apn));
5387 assertExpectException(SecurityException.class, null, () ->
5388 dpm.updateOverrideApn(admin1, 0, apn));
5389 assertExpectException(SecurityException.class, null, () ->
5390 dpm.removeOverrideApn(admin1, 0));
5391 assertExpectException(SecurityException.class, null, () ->
5392 dpm.getOverrideApns(admin1));
5393 assertExpectException(SecurityException.class, null, () ->
5394 dpm.setOverrideApnsEnabled(admin1, false));
5395 assertExpectException(SecurityException.class, null, () ->
5396 dpm.isOverrideApnEnabled(admin1));
5397 }
5398
Robin Lee2c68dad2017-03-17 12:50:24 +00005399 private void verifyCanGetOwnerInstalledCaCerts(
5400 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005401 final String alias = "cert";
5402 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005403
5404 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005405 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005406 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5407 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005408 }
5409 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5410
5411 // caller: device admin or delegated certificate installer
5412 callerContext.applicationInfo = new ApplicationInfo();
5413 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5414
5415 // system_server
5416 final DpmMockContext serviceContext = mContext;
5417 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005418 getServices().addPackageContext(callerUser, admin1Context);
5419 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005420
5421 // Install a CA cert.
5422 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005423 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005424 .thenReturn(alias);
5425 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005426 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00005427 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00005428 });
5429
Pavel Grafov75c0a892017-05-18 17:28:27 +01005430 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5431 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5432 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005433 flushTasks();
5434
Robin Lee2c68dad2017-03-17 12:50:24 +00005435 final List<String> ownerInstalledCaCerts = new ArrayList<>();
5436
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005437 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00005438 runAsCaller(admin1Context, dpms, (dpm) -> {
5439 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005440 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00005441 ownerInstalledCaCerts.addAll(installedCaCerts);
5442 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005443
5444 // Restarting the DPMS should not lose information.
5445 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01005446 runAsCaller(admin1Context, dpms, (dpm) ->
5447 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005448
5449 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005450 runAsCaller(serviceContext, dpms, (dpm) -> {
5451 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005452
Robin Lee2c68dad2017-03-17 12:50:24 +00005453 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005454 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00005455 });
5456
Pavel Grafov75c0a892017-05-18 17:28:27 +01005457 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5458 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5459 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005460 flushTasks();
5461
5462 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
5463 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005464 runAsCaller(admin1Context, dpms, (dpm) -> {
5465 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
5466 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005467 }
5468
Robin Lee2c68dad2017-03-17 12:50:24 +00005469 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
5470 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005471 final String alias = "cert";
5472 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005473
5474 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005475 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005476 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5477 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005478 }
5479 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5480
5481 // caller: device admin or delegated certificate installer
5482 callerContext.applicationInfo = new ApplicationInfo();
5483 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5484
5485 // system_server
5486 final DpmMockContext serviceContext = mContext;
5487 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005488 getServices().addPackageContext(callerUser, admin1Context);
5489 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005490
5491 // Install a CA cert as caller
5492 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005493 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005494 .thenReturn(alias);
5495 assertTrue(dpm.installCaCert(callerName, caCert));
5496 });
5497
5498 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005499 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005500 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005501 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5502 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5503 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005504 flushTasks();
5505
Robin Lee2c68dad2017-03-17 12:50:24 +00005506 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005507 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005508
5509 runAsCaller(serviceContext, dpms, (dpm) -> {
5510 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5511 assertNotNull(ownerInstalledCaCerts);
5512 assertTrue(ownerInstalledCaCerts.isEmpty());
5513 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005514 }
5515
Eran Messeri94d56762017-12-21 20:50:54 +00005516 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5517 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5518 Arrays.sort(gotFlags);
5519 Arrays.sort(expectedFlags);
5520 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5521 }
5522
5523 public void testTranslationOfIdAttestationFlag() {
5524 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5525 int[] correspondingAttUtilsTypes = new int[]{
5526 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5527 AttestationUtils.ID_TYPE_MEID};
5528
5529 // Test translation of zero flags
5530 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5531
5532 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5533 // non-null array
5534 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5535
5536 // Test translation of a single flag
5537 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5538 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5539 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5540
5541 // Test translation of two flags
5542 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5543 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5544 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5545 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5546
5547 // Test translation of all three flags
5548 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5549 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5550 AttestationUtils.ID_TYPE_MEID});
5551 // Test translation of all three flags
5552 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5553 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5554 AttestationUtils.ID_TYPE_MEID});
5555 }
5556
arangelov08d534b2018-01-22 15:20:53 +00005557 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5558 setDeviceOwner();
5559 initializeDpms();
5560 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5561 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5562 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5563 }
5564
Pavel Grafov42da7f72020-02-05 22:19:49 +00005565 // @FlakyTest(bugId = 148934649)
5566 // public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5567 // DpmTestUtils.writeInputStreamToFile(
5568 // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5569 // getDeviceOwnerPoliciesFile());
5570 // DpmTestUtils.writeInputStreamToFile(
5571 // getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5572 // getDeviceOwnerFile());
5573 // assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5574 // }
arangelov08d534b2018-01-22 15:20:53 +00005575
Pavel Grafov42da7f72020-02-05 22:19:49 +00005576 // @FlakyTest(bugId = 148934649)
5577 // public void testRevertDeviceOwnership_deviceNotMigrated()
5578 // throws Exception {
5579 // DpmTestUtils.writeInputStreamToFile(
5580 // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5581 // getDeviceOwnerPoliciesFile());
5582 // DpmTestUtils.writeInputStreamToFile(
5583 // getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5584 // getDeviceOwnerFile());
5585 // assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5586 // }
arangelov08d534b2018-01-22 15:20:53 +00005587
5588 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5589 throws Exception {
5590 DpmTestUtils.writeInputStreamToFile(
5591 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5592 getDeviceOwnerPoliciesFile());
5593 DpmTestUtils.writeInputStreamToFile(
5594 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5595 getDeviceOwnerFile());
5596 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5597 }
5598
5599 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5600 setupProfileOwner();
5601 initializeDpms();
5602 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5603 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5604 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5605 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5606 }
5607
Pavel Grafov42da7f72020-02-05 22:19:49 +00005608 // @FlakyTest(bugId = 148934649)
5609 // public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5610 // getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5611 // UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
5612 // DpmTestUtils.writeInputStreamToFile(
5613 // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5614 // getProfileOwnerPoliciesFile());
5615 // DpmTestUtils.writeInputStreamToFile(
5616 // getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5617 // getProfileOwnerFile());
5618 // assertProfileOwnershipRevertedWithFakeTransferMetadata();
5619 // }
arangelov08d534b2018-01-22 15:20:53 +00005620
Pavel Grafov42da7f72020-02-05 22:19:49 +00005621 // @FlakyTest(bugId = 148934649)
5622 // public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5623 // getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5624 // UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
5625 // DpmTestUtils.writeInputStreamToFile(
5626 // getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5627 // getProfileOwnerPoliciesFile());
5628 // DpmTestUtils.writeInputStreamToFile(
5629 // getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5630 // getProfileOwnerFile());
5631 // assertProfileOwnershipRevertedWithFakeTransferMetadata();
5632 // }
arangelov08d534b2018-01-22 15:20:53 +00005633
5634 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005635 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5636 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005637 DpmTestUtils.writeInputStreamToFile(
5638 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5639 getProfileOwnerPoliciesFile());
5640 DpmTestUtils.writeInputStreamToFile(
5641 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5642 getProfileOwnerFile());
5643 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5644 }
5645
Eran Messeribb271892018-10-17 18:27:50 +01005646 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5647 setupProfileOwner();
5648 configureContextForAccess(mContext, false);
5649
5650 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005651 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005652 }
5653
5654 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5655 setupProfileOwner();
5656 configureContextForAccess(mContext, false);
5657
5658 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005659 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005660 }
5661
5662 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5663 setupProfileOwner();
5664
5665 // This method will throw if the system context could not call
Eran Messeri18d21312019-11-14 22:44:40 +00005666 // markProfileOwnerOfOrganizationOwnedDevice successfully.
5667 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005668 }
5669
Eran Messerib8c46e02019-11-07 12:06:18 +00005670 private void configureContextForAccess(DpmMockContext context, boolean granted) {
Eran Messeribb271892018-10-17 18:27:50 +01005671 when(context.spiedContext.checkCallingPermission(
Eran Messeri18d21312019-11-14 22:44:40 +00005672 permission.MARK_DEVICE_ORGANIZATION_OWNED))
Eran Messeribb271892018-10-17 18:27:50 +01005673 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5674 : PackageManager.PERMISSION_DENIED);
Eran Messerib8c46e02019-11-07 12:06:18 +00005675
5676 when(getServices().userManager.getProfileParent(any()))
5677 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005678 }
5679
5680 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5681 setupProfileOwner();
5682
5683 final long ident = mServiceContext.binder.clearCallingIdentity();
5684 configureContextForAccess(mServiceContext, true);
5685
5686 mServiceContext.binder.callingUid =
5687 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5688 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5689 try {
5690 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005691 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005692 });
5693 } finally {
5694 mServiceContext.binder.restoreCallingIdentity(ident);
5695 }
5696 }
5697
5698 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5699 throws Exception {
5700 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5701 setupDeviceOwner();
5702 configureContextForAccess(mContext, false);
5703
5704 // Device owner should be allowed to request Device ID attestation.
5705 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5706 DpmMockContext.CALLER_SYSTEM_USER_UID);
5707
5708 // Another package must not be allowed to request Device ID attestation.
5709 assertExpectException(SecurityException.class, null,
5710 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5711 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5712 // Another component that is not the admin must not be allowed to request Device ID
5713 // attestation.
5714 assertExpectException(SecurityException.class, null,
5715 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5716 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5717 }
5718
5719 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5720 throws Exception {
5721 configureContextForAccess(mContext, false);
5722
5723 // Make sure a security exception is thrown if the device has no profile owner.
5724 assertExpectException(SecurityException.class, null,
5725 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5726 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5727
5728 setupProfileOwner();
Eran Messeri18d21312019-11-14 22:44:40 +00005729 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005730
5731 // The profile owner is allowed to request Device ID attestation.
5732 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5733 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5734 DpmMockContext.CALLER_UID);
5735 // But not another package.
5736 assertExpectException(SecurityException.class, null,
5737 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5738 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5739 // Or another component which is not the admin.
5740 assertExpectException(SecurityException.class, null,
5741 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5742 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5743 }
5744
5745 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5746 final long ident = mServiceContext.binder.clearCallingIdentity();
5747
5748 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5749 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5750 try {
5751 runAsCaller(mServiceContext, dpms, action);
5752 } finally {
5753 mServiceContext.binder.restoreCallingIdentity(ident);
5754 }
5755 }
5756
5757 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5758 setupProfileOwner();
5759 markDelegatedCertInstallerAsInstalled();
5760
5761 // Configure a delegated cert installer.
5762 runAsCaller(mServiceContext, dpms,
5763 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5764 Arrays.asList(DELEGATION_CERT_INSTALL)));
5765
Eran Messeri18d21312019-11-14 22:44:40 +00005766 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005767
5768 // Make sure that the profile owner can still request Device ID attestation.
5769 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5770 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5771 DpmMockContext.CALLER_UID);
5772
5773 runAsDelegatedCertInstaller(dpm -> {
5774 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5775 DpmMockContext.DELEGATE_PACKAGE_NAME,
5776 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5777 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5778 });
5779 }
5780
5781 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5782 throws Exception {
5783 setupProfileOwner();
5784 markDelegatedCertInstallerAsInstalled();
5785
5786 // Configure a delegated cert installer.
5787 runAsCaller(mServiceContext, dpms,
5788 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5789 Arrays.asList(DELEGATION_CERT_INSTALL)));
5790
5791
5792 assertExpectException(SecurityException.class, null,
5793 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5794 admin1.getPackageName(),
5795 DpmMockContext.CALLER_UID));
5796
5797 runAsDelegatedCertInstaller(dpm -> {
5798 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5799 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5800 DpmMockContext.DELEGATE_PACKAGE_NAME,
5801 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5802 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5803 });
5804 }
5805
Alex Johnston07cb9f02019-11-01 17:40:38 +00005806 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005807 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5808 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5809 new String[0]);
Alex Johnston07cb9f02019-11-01 17:40:38 +00005810 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5811 setAsProfileOwner(admin1);
5812
Alex Johnston755e3772019-11-29 03:27:22 +00005813 parentDpm.getPasswordComplexity();
Alex Johnston07cb9f02019-11-01 17:40:38 +00005814
5815 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005816 }
5817
5818 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005819 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5820 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5821 new String[0]);
Bernard Chaue9586552018-11-29 10:59:31 +00005822 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5823 .thenReturn(false);
5824 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5825 }
5826
5827 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005828 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5829 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5830 new String[0]);
Bernard Chaue9586552018-11-29 10:59:31 +00005831 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5832 .thenReturn(true);
5833 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5834 }
5835
5836
5837 public void testGetPasswordComplexity_currentUserNoPassword() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005838 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5839 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5840 new String[0]);
Bernard Chaue9586552018-11-29 10:59:31 +00005841 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5842 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005843 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005844 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5845 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5846
5847 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5848 }
5849
5850 public void testGetPasswordComplexity_currentUserHasPassword() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005851 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5852 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5853 new String[0]);
Bernard Chaue9586552018-11-29 10:59:31 +00005854 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5855 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005856 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005857 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5858 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005859 when(getServices().lockSettingsInternal
5860 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005861 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005862
5863 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5864 }
5865
5866 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
Alex Johnstond9283a72020-02-04 15:09:34 +00005867 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
5868 when(getServices().packageManager.getPackagesForUid(DpmMockContext.CALLER_UID)).thenReturn(
5869 new String[0]);
Bernard Chaue9586552018-11-29 10:59:31 +00005870 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5871 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005872 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005873
5874 UserInfo parentUser = new UserInfo();
5875 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5876 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5877 .thenReturn(parentUser.id);
5878
Rubin Xu19854862019-08-15 16:37:23 +01005879 when(getServices().lockSettingsInternal
5880 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005881 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005882 when(getServices().lockSettingsInternal
5883 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005884 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005885
5886 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5887 }
5888
yuemingwd2bfbc82019-01-02 11:42:25 +00005889 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5890 setAsProfileOwner(admin1);
5891 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5892 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5893 }
5894
5895 public void testCrossProfileCalendarPackages_reopenDpms() {
5896 setAsProfileOwner(admin1);
5897 dpm.setCrossProfileCalendarPackages(admin1, null);
5898 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5899 assertTrue(packages == null);
5900 initializeDpms();
5901 packages = dpm.getCrossProfileCalendarPackages(admin1);
5902 assertTrue(packages == null);
5903
5904 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5905 packages = dpm.getCrossProfileCalendarPackages(admin1);
5906 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5907 initializeDpms();
5908 packages = dpm.getCrossProfileCalendarPackages(admin1);
5909 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5910
5911 final String dummyPackageName = "test";
5912 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5913 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5914 packages = dpm.getCrossProfileCalendarPackages(admin1);
5915 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5916 initializeDpms();
5917 packages = dpm.getCrossProfileCalendarPackages(admin1);
5918 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5919 }
5920
5921 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5922 assertTrue(expected != null);
5923 assertTrue(actual != null);
5924 assertTrue(expected.containsAll(actual));
5925 assertTrue(actual.containsAll(expected));
5926 }
5927
yuemingwdded98f2019-01-30 17:08:12 +00005928 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5929 setAsProfileOwner(admin1);
5930 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5931 when(getServices().settings.settingsSecureGetIntForUser(
5932 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5933 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5934 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5935 }
5936
5937 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5938 final String testPackage = "TEST_PACKAGE";
5939 setAsProfileOwner(admin1);
5940 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5941 when(getServices().settings.settingsSecureGetIntForUser(
5942 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5943 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5944 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5945 }
5946
5947 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5948 final String testPackage = "TEST_PACKAGE";
5949 setAsProfileOwner(admin1);
5950 dpm.setCrossProfileCalendarPackages(admin1, null);
5951 when(getServices().settings.settingsSecureGetIntForUser(
5952 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5953 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5954 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5955 }
5956
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005957 public void testSetUserControlDisabledPackages_asDO() throws Exception {
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005958 final List<String> testPackages = new ArrayList<>();
5959 testPackages.add("package_1");
5960 testPackages.add("package_2");
5961
5962 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5963 setDeviceOwner();
5964
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005965 dpm.setUserControlDisabledPackages(admin1, testPackages);
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005966
5967 verify(getServices().packageManagerInternal).setDeviceOwnerProtectedPackages(testPackages);
5968
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005969 assertEquals(testPackages, dpm.getUserControlDisabledPackages(admin1));
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005970 }
5971
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005972 public void testSetUserControlDisabledPackages_failingAsPO() throws Exception {
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005973 final List<String> testPackages = new ArrayList<>();
5974 testPackages.add("package_1");
5975 testPackages.add("package_2");
5976
5977 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5978 setAsProfileOwner(admin1);
5979
5980 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005981 () -> dpm.setUserControlDisabledPackages(admin1, testPackages));
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005982
5983 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Srinivas Paladugu8faac832020-03-06 10:53:26 -08005984 () -> dpm.getUserControlDisabledPackages(admin1));
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005985 }
5986
Eran Messeri18d21312019-11-14 22:44:40 +00005987 private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
Eran Messeribb271892018-10-17 18:27:50 +01005988 final long ident = mServiceContext.binder.clearCallingIdentity();
Pavel Grafova5b15b22020-02-03 16:06:20 +00005989 mServiceContext.binder.callingUid = UserHandle.getUid(userId, DpmMockContext.SYSTEM_UID);
Eran Messeri18d21312019-11-14 22:44:40 +00005990
5991 configureContextForAccess(mServiceContext, true);
Eran Messeribb271892018-10-17 18:27:50 +01005992 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005993 dpm.markProfileOwnerOnOrganizationOwnedDevice(who);
Eran Messeribb271892018-10-17 18:27:50 +01005994 });
5995 mServiceContext.binder.restoreCallingIdentity(ident);
5996 }
5997
Alex Kershaw434a2242019-12-04 11:34:45 +00005998 public void testGetCrossProfilePackages_notSet_returnsEmpty() {
5999 setAsProfileOwner(admin1);
6000 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
6001 }
6002
6003 public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() {
6004 setAsProfileOwner(admin1);
6005
6006 initializeDpms();
6007
6008 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
6009 }
6010
6011 public void testGetCrossProfilePackages_whenSet_returnsEqual() {
6012 setAsProfileOwner(admin1);
6013 Set<String> packages = Collections.singleton("TEST_PACKAGE");
6014
6015 dpm.setCrossProfilePackages(admin1, packages);
6016
6017 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
6018 }
6019
6020 public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() {
6021 setAsProfileOwner(admin1);
6022 Set<String> packages = Collections.singleton("TEST_PACKAGE");
6023
6024 dpm.setCrossProfilePackages(admin1, packages);
6025 initializeDpms();
6026
6027 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
6028 }
6029
kholoud mohamedfff05762019-12-10 11:38:04 +00006030 public void testGetAllCrossProfilePackages_notSet_returnsEmpty() throws Exception {
6031 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00006032 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00006033
6034 setCrossProfileAppsList();
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006035 setVendorCrossProfileAppsList();
kholoud mohamedfff05762019-12-10 11:38:04 +00006036
6037 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
6038 }
6039
6040 public void testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()
6041 throws Exception {
6042 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00006043 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00006044
6045 setCrossProfileAppsList();
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006046 setVendorCrossProfileAppsList();
kholoud mohamedfff05762019-12-10 11:38:04 +00006047 initializeDpms();
6048
6049 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
6050 }
6051
6052 public void testGetAllCrossProfilePackages_whenSet_returnsCombinedSet() throws Exception {
6053 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
6054 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00006055 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00006056
6057 dpm.setCrossProfilePackages(admin1, packages);
6058 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006059 setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
kholoud mohamedfff05762019-12-10 11:38:04 +00006060
6061 assertEquals(Sets.newSet(
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006062 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE",
6063 "TEST_VENDOR_DEFAULT_PACKAGE"),
kholoud mohamedfff05762019-12-10 11:38:04 +00006064 dpm.getAllCrossProfilePackages());
6065
6066 }
6067
6068 public void testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet()
6069 throws Exception {
6070 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
6071 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00006072 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00006073
6074 dpm.setCrossProfilePackages(admin1, packages);
6075 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006076 setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
kholoud mohamedfff05762019-12-10 11:38:04 +00006077 initializeDpms();
6078
6079 assertEquals(Sets.newSet(
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006080 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE",
6081 "TEST_VENDOR_DEFAULT_PACKAGE"),
kholoud mohamedfff05762019-12-10 11:38:04 +00006082 dpm.getAllCrossProfilePackages());
6083 }
6084
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006085 public void testGetDefaultCrossProfilePackages_noPackagesSet_returnsEmpty() {
6086 setCrossProfileAppsList();
6087 setVendorCrossProfileAppsList();
6088
6089 assertThat(dpm.getDefaultCrossProfilePackages()).isEmpty();
6090 }
6091
6092 public void testGetDefaultCrossProfilePackages_packagesSet_returnsCombinedSet() {
6093 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
6094 setVendorCrossProfileAppsList("TEST_VENDOR_DEFAULT_PACKAGE");
6095
6096 assertThat(dpm.getDefaultCrossProfilePackages()).isEqualTo(Sets.newSet(
6097 "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE", "TEST_VENDOR_DEFAULT_PACKAGE"
6098 ));
6099 }
6100
Rubin Xu41bdd972020-01-03 17:18:33 +00006101 public void testSetCommonCriteriaMode_asDeviceOwner() throws Exception {
6102 setDeviceOwner();
6103
Rubin Xuf0797322020-03-10 15:37:54 +00006104 assertFalse(dpm.isCommonCriteriaModeEnabled(admin1));
6105 assertFalse(dpm.isCommonCriteriaModeEnabled(null));
Rubin Xu41bdd972020-01-03 17:18:33 +00006106
Rubin Xuf0797322020-03-10 15:37:54 +00006107 dpm.setCommonCriteriaModeEnabled(admin1, true);
6108
Rubin Xu41bdd972020-01-03 17:18:33 +00006109 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
Rubin Xuf0797322020-03-10 15:37:54 +00006110 assertTrue(dpm.isCommonCriteriaModeEnabled(null));
Rubin Xu41bdd972020-01-03 17:18:33 +00006111 }
6112
6113 public void testSetCommonCriteriaMode_asPoOfOrgOwnedDevice() throws Exception {
Rubin Xuf0797322020-03-10 15:37:54 +00006114 final int managedProfileUserId = 15;
6115 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
6116 addManagedProfile(admin1, managedProfileAdminUid, admin1);
6117 configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
6118 mContext.binder.callingUid = managedProfileAdminUid;
6119
6120 assertFalse(dpm.isCommonCriteriaModeEnabled(admin1));
6121 assertFalse(dpm.isCommonCriteriaModeEnabled(null));
Rubin Xu41bdd972020-01-03 17:18:33 +00006122
6123 dpm.setCommonCriteriaModeEnabled(admin1, true);
Rubin Xu41bdd972020-01-03 17:18:33 +00006124
Rubin Xu41bdd972020-01-03 17:18:33 +00006125 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
Rubin Xuf0797322020-03-10 15:37:54 +00006126 assertTrue(dpm.isCommonCriteriaModeEnabled(null));
Rubin Xu41bdd972020-01-03 17:18:33 +00006127 }
6128
Pavel Grafov4513e242020-01-31 11:41:51 +00006129 public void testCanProfileOwnerResetPasswordWhenLocked_nonDirectBootAwarePo()
6130 throws Exception {
6131 setDeviceEncryptionPerUser();
6132 setupProfileOwner();
6133 setupPasswordResetToken();
6134
6135 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6136 assertFalse("po is not direct boot aware",
6137 dpm.canProfileOwnerResetPasswordWhenLocked(DpmMockContext.CALLER_USER_HANDLE));
6138 }
6139
6140 public void testCanProfileOwnerResetPasswordWhenLocked_noActiveToken() throws Exception {
6141 setDeviceEncryptionPerUser();
6142 setupProfileOwner();
6143 makeAdmin1DirectBootAware();
6144
6145 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6146 assertFalse("po doesn't have an active password reset token",
6147 dpm.canProfileOwnerResetPasswordWhenLocked(DpmMockContext.CALLER_USER_HANDLE));
6148 }
6149
6150 public void testCanProfileOwnerResetPasswordWhenLocked_nonFbeDevice() throws Exception {
6151 setupProfileOwner();
6152 makeAdmin1DirectBootAware();
6153 setupPasswordResetToken();
6154
6155 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6156 assertFalse("device is not FBE",
6157 dpm.canProfileOwnerResetPasswordWhenLocked(DpmMockContext.CALLER_USER_HANDLE));
6158 }
6159
6160 public void testCanProfileOwnerResetPasswordWhenLocked() throws Exception {
6161 setDeviceEncryptionPerUser();
6162 setupProfileOwner();
6163 makeAdmin1DirectBootAware();
6164 setupPasswordResetToken();
6165
6166 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6167 assertTrue("direct boot aware po with active password reset token",
6168 dpm.canProfileOwnerResetPasswordWhenLocked(DpmMockContext.CALLER_USER_HANDLE));
6169 }
6170
6171 private void setupPasswordResetToken() {
6172 final byte[] token = new byte[32];
6173 final long handle = 123456;
6174
6175 when(getServices().lockPatternUtils
6176 .addEscrowToken(eq(token), eq(DpmMockContext.CALLER_USER_HANDLE),
6177 nullable(EscrowTokenStateChangeCallback.class)))
6178 .thenReturn(handle);
6179
6180 dpm.setResetPasswordToken(admin1, token);
6181
6182 when(getServices().lockPatternUtils
6183 .isEscrowTokenActive(eq(handle), eq(DpmMockContext.CALLER_USER_HANDLE)))
6184 .thenReturn(true);
6185
6186 assertTrue("failed to activate token", dpm.isResetPasswordTokenActive(admin1));
6187 }
6188
6189 private void makeAdmin1DirectBootAware()
6190 throws PackageManager.NameNotFoundException, android.os.RemoteException {
6191 Mockito.reset(getServices().ipackageManager);
6192
6193 final ApplicationInfo ai = DpmTestUtils.cloneParcelable(
6194 mRealTestContext.getPackageManager().getApplicationInfo(
6195 admin1.getPackageName(),
6196 PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS));
6197 ai.privateFlags = PRIVATE_FLAG_DIRECT_BOOT_AWARE;
6198
6199 doReturn(ai).when(getServices().ipackageManager).getApplicationInfo(
6200 eq(admin1.getPackageName()),
6201 anyInt(),
6202 eq(DpmMockContext.CALLER_USER_HANDLE));
6203 }
6204
6205 private void setDeviceEncryptionPerUser() {
6206 when(getServices().storageManager.isFileBasedEncryptionEnabled()).thenReturn(true);
6207 }
6208
kholoud mohamedfff05762019-12-10 11:38:04 +00006209 private void setCrossProfileAppsList(String... packages) {
6210 when(mContext.getResources()
6211 .getStringArray(eq(R.array.cross_profile_apps)))
6212 .thenReturn(packages);
6213 }
6214
Jonathan Scott38f9ab52020-01-29 16:36:09 +00006215 private void setVendorCrossProfileAppsList(String... packages) {
6216 when(mContext.getResources()
6217 .getStringArray(eq(R.array.vendor_cross_profile_apps)))
6218 .thenReturn(packages);
6219 }
6220
Eran Messeri65d94932020-02-13 15:56:36 +00006221 public void testSetAccountTypesWithManagementDisabledOnManagedProfile() throws Exception {
6222 setupProfileOwner();
6223
6224 final String accountType = "com.example.account.type";
6225 int originalUid = mContext.binder.callingUid;
6226 dpm.setAccountManagementDisabled(admin1, accountType, true);
6227 assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
6228 accountType);
6229 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
6230 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6231 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6232 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6233
6234 mContext.binder.callingUid = originalUid;
6235 dpm.setAccountManagementDisabled(admin1, accountType, false);
6236 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6237 }
6238
6239 public void testSetAccountTypesWithManagementDisabledOnOrgOwnedManagedProfile()
6240 throws Exception {
6241 final int managedProfileUserId = 15;
6242 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 19436);
6243
6244 addManagedProfile(admin1, managedProfileAdminUid, admin1);
6245 mContext.binder.callingUid = managedProfileAdminUid;
6246
6247 configureProfileOwnerOfOrgOwnedDevice(admin1, managedProfileUserId);
6248
6249 int originalUid = mContext.binder.callingUid;
6250 final String accountType = "com.example.account.type";
6251 dpm.getParentProfileInstance(admin1).setAccountManagementDisabled(admin1, accountType,
6252 true);
6253 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6254 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
6255 assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
6256 accountType);
6257 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6258 assertThat(dpm.getAccountTypesWithManagementDisabled()).asList().containsExactly(
6259 accountType);
6260
6261 mContext.binder.callingUid = originalUid;
6262 dpm.getParentProfileInstance(admin1).setAccountManagementDisabled(admin1, accountType,
6263 false);
6264 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
6265 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6266 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
6267 assertThat(dpm.getAccountTypesWithManagementDisabled()).isEmpty();
6268 }
6269
arangelov08d534b2018-01-22 15:20:53 +00006270 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
6271 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
6272 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
6273 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
6274
6275 final long ident = mServiceContext.binder.clearCallingIdentity();
6276 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
6277 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
6278 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
6279 // To simulate a reboot, we just reinitialize dpms and call systemReady
6280 initializeDpms();
6281
6282 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
6283 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
6284 assertFalse(dpm.isAdminActive(adminAnotherPackage));
6285 assertTrue(dpm.isAdminActive(admin1));
6286 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
6287 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
6288
6289 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
6290 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
6291 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
6292 assertFalse(getMockTransferMetadataManager().metadataFileExists());
6293
6294 mServiceContext.binder.restoreCallingIdentity(ident);
6295 }
6296
6297 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
6298 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
6299 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
6300 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
6301
6302 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
6303 DpmMockContext.CALLER_SYSTEM_USER_UID);
6304 setUpPackageManagerForAdmin(admin1, uid);
6305 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
6306 // To simulate a reboot, we just reinitialize dpms and call systemReady
6307 initializeDpms();
6308
6309 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
6310 assertTrue(dpm.isAdminActive(admin1));
6311 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
6312 assertFalse(dpm.isAdminActive(adminAnotherPackage));
6313 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
6314 assertFalse(getMockTransferMetadataManager().metadataFileExists());
6315 }
6316
6317 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
6318 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
6319 metadataManager.deleteMetadataFile();
6320
6321 final TransferOwnershipMetadataManager.Metadata metadata =
6322 new TransferOwnershipMetadataManager.Metadata(
6323 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
6324 callerUserHandle,
6325 adminType);
6326 metadataManager.saveMetadataFile(metadata);
6327 }
6328
6329 private File getDeviceOwnerFile() {
6330 return dpms.mOwners.getDeviceOwnerFile();
6331 }
6332
6333 private File getProfileOwnerFile() {
6334 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
6335 }
6336
6337 private File getProfileOwnerPoliciesFile() {
6338 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
6339 DpmMockContext.CALLER_USER_HANDLE);
6340 return getPoliciesFile(parentDir);
6341 }
6342
6343 private File getDeviceOwnerPoliciesFile() {
6344 return getPoliciesFile(getServices().systemUserDataDir);
6345 }
6346
6347 private File getPoliciesFile(File parentDir) {
6348 return new File(parentDir, "device_policies.xml");
6349 }
6350
Victor Chang3e794af2016-03-04 13:48:17 +00006351 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01006352 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00006353 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
6354 dpms.notifyChangeToContentObserver(
6355 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
6356 }
6357
6358 private void assertProvisioningAllowed(String action, boolean expected) {
6359 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
6360 dpm.isProvisioningAllowed(action));
6361 }
Tony Mak2f26b792016-11-28 17:54:51 +00006362
Nicolas Prevot45d29072017-01-18 16:11:19 +00006363 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
6364 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01006365 final String previousPackageName = mContext.packageName;
6366 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00006367
6368 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
6369 mContext.packageName = packageName;
6370 mMockContext.binder.callingUid = uid;
6371 assertProvisioningAllowed(action, expected);
6372
6373 // Set the previous package name / calling uid to go back to the initial state.
6374 mContext.packageName = previousPackageName;
6375 mMockContext.binder.callingUid = previousUid;
6376 }
6377
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006378 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00006379 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
6380 }
6381
6382 private void assertCheckProvisioningPreCondition(
6383 String action, String packageName, int provisioningCondition) {
6384 assertEquals("checkProvisioningPreCondition("
6385 + action + ", " + packageName + ") returning unexpected result",
6386 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006387 }
6388
Tony Mak2f26b792016-11-28 17:54:51 +00006389 /**
6390 * Setup a managed profile with the specified admin and its uid.
6391 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
6392 * @param adminUid uid of the admin package.
6393 * @param copyFromAdmin package information for {@code admin} will be built based on this
6394 * component's information.
6395 */
6396 private void addManagedProfile(
6397 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
6398 final int userId = UserHandle.getUserId(adminUid);
Alex Johnston755e3772019-11-29 03:27:22 +00006399 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
6400 UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00006401 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
6402 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
6403 dpm.setActiveAdmin(admin, false, userId);
6404 assertTrue(dpm.setProfileOwner(admin, null, userId));
6405 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
6406 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00006407
6408 /**
Robin Leeabaa0692017-02-20 20:54:22 +00006409 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00006410 */
Robin Leeabaa0692017-02-20 20:54:22 +00006411 private static StringParceledListSlice asSlice(String[] s) {
6412 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00006413 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006414
6415 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00006416 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
6417 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006418
Robin Lee2c68dad2017-03-17 12:50:24 +00006419 // We can't let exceptions happen on the background thread. Throw them here if they happen
6420 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01006421 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006422 }
Victor Chang3e794af2016-03-04 13:48:17 +00006423}