blob: def5b617becdeb1a029b9dc53fb9b772d8cd8a61 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6f334842019-08-06 14:37:06 +010028import static android.app.admin.PasswordMetrics.computeForPassword;
Pavel Grafov6a40f092016-10-25 15:46:51 +010029
Pavel Grafov6f334842019-08-06 14:37:06 +010030import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080031import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070032import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010033
Alex Johnston011f5c62019-12-18 17:05:57 +000034import static com.google.common.truth.Truth.assertThat;
35
Pavel Grafov75c0a892017-05-18 17:28:27 +010036import static org.mockito.Matchers.any;
Eran Messeri6ad0e192019-12-01 20:01:21 +000037import static org.mockito.Matchers.anyBoolean;
Pavel Grafov75c0a892017-05-18 17:28:27 +010038import static org.mockito.Matchers.anyInt;
39import static org.mockito.Matchers.anyLong;
40import static org.mockito.Matchers.anyObject;
41import static org.mockito.Matchers.anyString;
42import static org.mockito.Matchers.eq;
43import static org.mockito.Matchers.isNull;
44import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010045import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010046import static org.mockito.Mockito.doAnswer;
47import static org.mockito.Mockito.doReturn;
48import static org.mockito.Mockito.never;
49import static org.mockito.Mockito.nullable;
50import static org.mockito.Mockito.reset;
51import static org.mockito.Mockito.timeout;
52import static org.mockito.Mockito.times;
53import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080054import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010055import static org.mockito.Mockito.verifyZeroInteractions;
56import static org.mockito.Mockito.when;
57import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000058import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010059
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.Manifest.permission;
61import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010062import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000063import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070064import android.app.admin.DeviceAdminReceiver;
65import android.app.admin.DevicePolicyManager;
66import android.app.admin.DevicePolicyManagerInternal;
Alex Johnston011f5c62019-12-18 17:05:57 +000067import android.app.admin.FactoryResetProtectionPolicy;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010068import android.app.admin.PasswordMetrics;
Neil Fullere3767562019-11-23 11:33:57 +000069import android.app.timedetector.ManualTimeSuggestion;
Neil Fuller106f18a2019-12-04 13:27:04 +000070import android.app.timezonedetector.ManualTimeZoneSuggestion;
71import android.app.timezonedetector.TimeZoneDetector;
Makoto Onukif76b06a2015-09-22 15:03:44 -070072import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070073import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000074import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000075import android.content.pm.ApplicationInfo;
76import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070077import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010078import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000079import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000080import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010081import android.graphics.Color;
82import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080083import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070084import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080085import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070086import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070087import android.os.UserManager;
Alex Johnstonece5cdb2019-11-20 14:37:13 +000088import android.os.UserManagerInternal;
Pavel Grafovc14b3172017-07-03 13:15:11 +010089import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080090import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010091import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000092import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000093import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000094import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080095import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010096import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070097import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098
Pavel Grafov57f1b662019-03-27 14:55:38 +000099import androidx.test.filters.SmallTest;
100
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +0100101import com.android.internal.R;
Rubin Xua58125d2019-09-06 20:11:48 +0100102import com.android.internal.widget.LockscreenCredential;
Alan Treadwayafad8782016-01-19 15:15:08 +0000103import com.android.server.LocalServices;
104import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +0000105import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Alan Treadwayafad8782016-01-19 15:15:08 +0000106
Robin Lee7f5c91c2017-02-08 21:27:02 +0000107import org.hamcrest.BaseMatcher;
108import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800109import org.mockito.Mockito;
kholoud mohamedfff05762019-12-10 11:38:04 +0000110import org.mockito.internal.util.collections.Sets;
Makoto Onukib643fb02015-09-22 15:03:44 -0700111import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112
arangelov08d534b2018-01-22 15:20:53 +0000113import java.io.File;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800114import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000115import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000116import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700117import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700119import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100120import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000121import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700122
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700124 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000125 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126 m FrameworksServicesTests &&
127 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000128 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700130 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131
132 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000133 *
134 * , or:
135 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700136 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000137@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100138@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700139public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000140 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
141 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
142 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100143 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800144 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Eran Messeri6ba10db2019-12-04 15:53:27 +0000145 public static final String NOT_ORG_OWNED_PROFILE_OWNER_MSG =
146 "not the profile owner on organization-owned device";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100147 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000148
Pavel Grafov75c0a892017-05-18 17:28:27 +0100149 // TODO replace all instances of this with explicit {@link #mServiceContext}.
150 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700151 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100152
153 private DpmMockContext mServiceContext;
154 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700155 public DevicePolicyManager dpm;
Alex Johnston755e3772019-11-29 03:27:22 +0000156 public DevicePolicyManager parentDpm;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700157 public DevicePolicyManagerServiceTestable dpms;
158
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100159 /*
160 * The CA cert below is the content of cacert.pem as generated by:
161 *
162 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
163 */
164 private static final String TEST_CA =
165 "-----BEGIN CERTIFICATE-----\n" +
166 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
167 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
168 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
169 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
170 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
171 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
172 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
173 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
174 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
175 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
176 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
177 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
178 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
179 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
180 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
181 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
182 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
183 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
184 "wQ==\n" +
185 "-----END CERTIFICATE-----\n";
186
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187 @Override
188 protected void setUp() throws Exception {
189 super.setUp();
190
191 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100192 mServiceContext = mContext;
193 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
194 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700195 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100196 doReturn(Collections.singletonList(new ResolveInfo()))
197 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
198 any(Intent.class),
199 anyInt(),
200 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700201
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800202 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100203 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800204
Makoto Onukia52562c2015-10-01 16:12:31 -0700205 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700206
Sudheer Shanka101c3532018-01-08 16:28:42 -0800207 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800208 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700209 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
210 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
211 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800212 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213
Pavel Grafov75c0a892017-05-18 17:28:27 +0100214 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
215 mAdmin1Context.packageName = admin1.getPackageName();
216 mAdmin1Context.applicationInfo = new ApplicationInfo();
217 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
218
Makoto Onukib643fb02015-09-22 15:03:44 -0700219 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100220
221 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700222 }
223
arangelov08d534b2018-01-22 15:20:53 +0000224 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
225 return dpms.mTransferOwnershipMetadataManager;
226 }
227
Robin Lee2c68dad2017-03-17 12:50:24 +0000228 @Override
229 protected void tearDown() throws Exception {
230 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000231 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000232 super.tearDown();
233 }
234
Makoto Onukia52562c2015-10-01 16:12:31 -0700235 private void initializeDpms() {
236 // Need clearCallingIdentity() to pass permission checks.
237 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700239
Pavel Grafov75c0a892017-05-18 17:28:27 +0100240 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
241 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
242 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700243
Pavel Grafov75c0a892017-05-18 17:28:27 +0100244 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700245
Alex Johnston755e3772019-11-29 03:27:22 +0000246 parentDpm = new DevicePolicyManagerTestable(mServiceContext, dpms,
247 /* parentInstance= */true);
248
Pavel Grafov75c0a892017-05-18 17:28:27 +0100249 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700250 }
251
Makoto Onukib643fb02015-09-22 15:03:44 -0700252 private void setUpUserManager() {
253 // Emulate UserManager.set/getApplicationRestriction().
254 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
255
256 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000257 doAnswer((Answer<Void>) invocation -> {
258 String pkg = (String) invocation.getArguments()[0];
259 Bundle bundle = (Bundle) invocation.getArguments()[1];
260 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000262 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700263
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000264 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100265 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100266 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700267
268 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000269 doAnswer((Answer<Bundle>) invocation -> {
270 String pkg = (String) invocation.getArguments()[0];
271 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700272
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000273 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100274 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700275 anyString(), any(UserHandle.class));
276
Eran Messeri6ad0e192019-12-01 20:01:21 +0000277 // Emulate UserManager.setUserRestriction/getUserRestrictions
278 final Map<UserHandle, Bundle> userRestrictions = new HashMap<>();
279
280 doAnswer((Answer<Void>) invocation -> {
281 String key = (String) invocation.getArguments()[0];
282 boolean value = (Boolean) invocation.getArguments()[1];
283 UserHandle user = (UserHandle) invocation.getArguments()[2];
284 Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
285 userBundle.putBoolean(key, value);
286
287 userRestrictions.put(user, userBundle);
288 return null;
289 }).when(getServices().userManager).setUserRestriction(
290 anyString(), anyBoolean(), any(UserHandle.class));
291
292 doAnswer((Answer<Boolean>) invocation -> {
293 String key = (String) invocation.getArguments()[0];
294 UserHandle user = (UserHandle) invocation.getArguments()[1];
295 Bundle userBundle = userRestrictions.getOrDefault(user, new Bundle());
296 return userBundle.getBoolean(key);
297 }).when(getServices().userManager).hasUserRestriction(
298 anyString(), any(UserHandle.class));
299
Makoto Onukid932f762015-09-29 16:53:38 -0700300 // Add the first secondary user.
Alex Johnston755e3772019-11-29 03:27:22 +0000301 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
302 UserManager.USER_TYPE_FULL_SECONDARY);
Makoto Onukib643fb02015-09-22 15:03:44 -0700303 }
304
305 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100306 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700307
Pavel Grafov75c0a892017-05-18 17:28:27 +0100308 mServiceContext.binder.callingUid =
309 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
310 runAsCaller(mServiceContext, dpms, dpm -> {
311 // PO needs to be a DA.
312 dpm.setActiveAdmin(admin, /*replace=*/ false);
313 // Fire!
314 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
315 // Check
316 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
317 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700318
Pavel Grafov75c0a892017-05-18 17:28:27 +0100319 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700320 }
321
322 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100323 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700324 .thenReturn(false);
325
326 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100327 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700328
329 // If the device has no DPMS feature, it shouldn't register the local service.
330 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
331 }
332
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800333 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800334 // Device owner in SYSTEM_USER
335 setDeviceOwner();
336 // Profile owner in CALLER_USER_HANDLE
337 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
338 setAsProfileOwner(admin2);
339 // Active admin in CALLER_USER_HANDLE
340 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
341 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
342 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
343 DpmMockContext.CALLER_USER_HANDLE);
344 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
345 DpmMockContext.CALLER_USER_HANDLE));
346
347 initializeDpms();
348
349 // Verify
350 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800351 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800352 eq(UserHandle.USER_SYSTEM));
353 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800354 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800355 adminAnotherPackage.getPackageName()),
356 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800357 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
358 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
359 }
360
361 public void testLoadAdminData_noAdmins() throws Exception {
362 final int ANOTHER_USER_ID = 15;
Alex Johnston755e3772019-11-29 03:27:22 +0000363 getServices().addUser(ANOTHER_USER_ID, 0, "");
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800364
365 initializeDpms();
366
367 // Verify
368 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
369 null, DpmMockContext.CALLER_USER_HANDLE);
370 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
371 null, ANOTHER_USER_ID);
372 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
373 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800374 }
375
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700376 /**
377 * Caller doesn't have proper permissions.
378 */
379 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700380 // 1. Failure cases.
381
382 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100383 assertExpectException(SecurityException.class, /* messageRegex= */ null,
384 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700385
386 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
387 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100388
389 assertExpectException(SecurityException.class, /* messageRegex= */ null,
390 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700391 }
392
Makoto Onukif76b06a2015-09-22 15:03:44 -0700393 /**
394 * Test for:
395 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800396 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700397 * {@link DevicePolicyManager#isAdminActive}
398 * {@link DevicePolicyManager#isAdminActiveAsUser}
399 * {@link DevicePolicyManager#getActiveAdmins}
400 * {@link DevicePolicyManager#getActiveAdminsAsUser}
401 */
402 public void testSetActiveAdmin() throws Exception {
403 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700404 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
405
Makoto Onukif76b06a2015-09-22 15:03:44 -0700406 // 2. Call the API.
407 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700408
409 // 3. Verify internal calls.
410
411 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700412 verify(mContext.spiedContext).sendBroadcastAsUser(
413 MockUtils.checkIntentAction(
414 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
415 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
416 verify(mContext.spiedContext).sendBroadcastAsUser(
417 MockUtils.checkIntentAction(
418 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100419 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
420 eq(null),
421 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700422
Pavel Grafov75c0a892017-05-18 17:28:27 +0100423 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700424 eq(admin1.getPackageName()),
425 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
426 eq(PackageManager.DONT_KILL_APP),
427 eq(DpmMockContext.CALLER_USER_HANDLE),
428 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700429
Sudheer Shanka101c3532018-01-08 16:28:42 -0800430 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
431 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
432
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700433 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700434
435 // Make sure it's active admin1.
436 assertTrue(dpm.isAdminActive(admin1));
437 assertFalse(dpm.isAdminActive(admin2));
438 assertFalse(dpm.isAdminActive(admin3));
439
440 // But not admin1 for a different user.
441
442 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
443 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
444 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
445
446 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
447 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
448
449 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
450
451 // Next, add one more admin.
452 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700453 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700454 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700455
456 dpm.setActiveAdmin(admin2, /* replace =*/ false);
457
458 // Now we have two admins.
459 assertTrue(dpm.isAdminActive(admin1));
460 assertTrue(dpm.isAdminActive(admin2));
461 assertFalse(dpm.isAdminActive(admin3));
462
463 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
464 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100465 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700466 eq(admin1.getPackageName()),
467 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
468 eq(PackageManager.DONT_KILL_APP),
469 eq(DpmMockContext.CALLER_USER_HANDLE),
470 anyString());
471
Sudheer Shanka101c3532018-01-08 16:28:42 -0800472 // times(2) because it was previously called for admin1 which is in the same package
473 // as admin2.
474 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
475 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
476
Makoto Onukif76b06a2015-09-22 15:03:44 -0700477 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100478 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
479 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700480
481 // 5. Add the same admin1 again with replace, which should succeed.
482 dpm.setActiveAdmin(admin1, /* replace =*/ true);
483
484 // TODO make sure it's replaced.
485
486 // 6. Test getActiveAdmins()
487 List<ComponentName> admins = dpm.getActiveAdmins();
488 assertEquals(2, admins.size());
489 assertEquals(admin1, admins.get(0));
490 assertEquals(admin2, admins.get(1));
491
Sudheer Shanka101c3532018-01-08 16:28:42 -0800492 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
493 // replaced
494 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
495
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496 // Another user has no admins.
497 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
498
499 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
500 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
501
502 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
503 }
504
Makoto Onukid932f762015-09-29 16:53:38 -0700505 public void testSetActiveAdmin_multiUsers() throws Exception {
506
507 final int ANOTHER_USER_ID = 100;
508 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
509
Alex Johnston755e3772019-11-29 03:27:22 +0000510 getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700511
512 // Set up pacakge manager for the other user.
513 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700514
515 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
516
517 dpm.setActiveAdmin(admin1, /* replace =*/ false);
518
519 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
520 dpm.setActiveAdmin(admin2, /* replace =*/ false);
521
522
523 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
524 assertTrue(dpm.isAdminActive(admin1));
525 assertFalse(dpm.isAdminActive(admin2));
526
527 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
528 assertFalse(dpm.isAdminActive(admin1));
529 assertTrue(dpm.isAdminActive(admin2));
530 }
531
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 /**
533 * Test for:
534 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800535 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 */
537 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
538 // 1. Make sure the caller has proper permissions.
539 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
540
541 dpm.setActiveAdmin(admin1, /* replace =*/ false);
542 assertTrue(dpm.isAdminActive(admin1));
543
544 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100545 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
546 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700547 }
548
549 /**
550 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800551 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
552 * BIND_DEVICE_ADMIN.
553 */
554 public void testSetActiveAdmin_permissionCheck() throws Exception {
555 // 1. Make sure the caller has proper permissions.
556 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
557
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100558 assertExpectException(IllegalArgumentException.class,
559 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
560 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800561 assertFalse(dpm.isAdminActive(adminNoPerm));
562
563 // Change the target API level to MNC. Now it can be set as DA.
564 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
565 VERSION_CODES.M);
566 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
567 assertTrue(dpm.isAdminActive(adminNoPerm));
568
569 // TODO Test the "load from the file" case where DA will still be loaded even without
570 // BIND_DEVICE_ADMIN and target API is N.
571 }
572
573 /**
574 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700575 * {@link DevicePolicyManager#removeActiveAdmin}
576 */
577 public void testRemoveActiveAdmin_SecurityException() {
578 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
579
580 // Add admin.
581
582 dpm.setActiveAdmin(admin1, /* replace =*/ false);
583
584 assertTrue(dpm.isAdminActive(admin1));
585
586 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
587
588 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100589 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
590 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700591
592 // Try to remove active admin with a different caller userid should fail too, without
593 // having MANAGE_DEVICE_ADMINS.
594 mContext.callerPermissions.clear();
595
Makoto Onukid932f762015-09-29 16:53:38 -0700596 // Change the caller, and call into DPMS directly with a different user-id.
597
Makoto Onukif76b06a2015-09-22 15:03:44 -0700598 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100599 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
600 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700601 }
602
603 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800604 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
605 * (because we can't send the remove broadcast).
606 */
607 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
608 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
609
610 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
611
612 // Add admin.
613
614 dpm.setActiveAdmin(admin1, /* replace =*/ false);
615
616 assertTrue(dpm.isAdminActive(admin1));
617
618 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
619
620 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100621 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800622 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100623 assertExpectException(IllegalStateException.class,
624 /* messageRegex= */ "User must be running and unlocked",
625 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800626
627 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800628 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
629 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800630
631 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100632 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800633 .thenReturn(true);
634
635 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700636 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800637 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
638 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800639 }
640
641 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700642 * Test for:
643 * {@link DevicePolicyManager#removeActiveAdmin}
644 */
Makoto Onukid932f762015-09-29 16:53:38 -0700645 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700646 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
647
648 // Add admin1.
649
650 dpm.setActiveAdmin(admin1, /* replace =*/ false);
651
652 assertTrue(dpm.isAdminActive(admin1));
653 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
654
655 // Different user, but should work, because caller has proper permissions.
656 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700657
658 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700660
661 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700662 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800663 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
664 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700665
666 // TODO DO Still can't be removed in this case.
667 }
668
669 /**
670 * Test for:
671 * {@link DevicePolicyManager#removeActiveAdmin}
672 */
673 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
674 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
675 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
676
677 // Add admin1.
678
679 dpm.setActiveAdmin(admin1, /* replace =*/ false);
680
681 assertTrue(dpm.isAdminActive(admin1));
682 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
683
684 // Broadcast from saveSettingsLocked().
685 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
686 MockUtils.checkIntentAction(
687 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
688 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
689
690 // Remove. No permissions, but same user, so it'll work.
691 mContext.callerPermissions.clear();
692 dpm.removeActiveAdmin(admin1);
693
Makoto Onukif76b06a2015-09-22 15:03:44 -0700694 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
695 MockUtils.checkIntentAction(
696 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
697 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
698 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100699 eq(AppOpsManager.OP_NONE),
700 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700701 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700702 eq(dpms.mHandler),
703 eq(Activity.RESULT_OK),
704 isNull(String.class),
705 isNull(Bundle.class));
706
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700707 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800708 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
709 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700710
711 // Again broadcast from saveSettingsLocked().
712 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
713 MockUtils.checkIntentAction(
714 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
715 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
716
717 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700718 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700719
Sudheer Shanka101c3532018-01-08 16:28:42 -0800720 public void testRemoveActiveAdmin_multipleAdminsInUser() {
721 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
722 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
723
724 // Add admin1.
725 dpm.setActiveAdmin(admin1, /* replace =*/ false);
726
727 assertTrue(dpm.isAdminActive(admin1));
728 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
729
730 // Add admin2.
731 dpm.setActiveAdmin(admin2, /* replace =*/ false);
732
733 assertTrue(dpm.isAdminActive(admin2));
734 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
735
736 // Broadcast from saveSettingsLocked().
737 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
738 MockUtils.checkIntentAction(
739 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
740 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
741
742 // Remove. No permissions, but same user, so it'll work.
743 mContext.callerPermissions.clear();
744 dpm.removeActiveAdmin(admin1);
745
746 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
747 MockUtils.checkIntentAction(
748 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
749 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
750 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100751 eq(AppOpsManager.OP_NONE),
752 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800753 any(BroadcastReceiver.class),
754 eq(dpms.mHandler),
755 eq(Activity.RESULT_OK),
756 isNull(String.class),
757 isNull(Bundle.class));
758
759 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
760 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800761 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800762 eq(DpmMockContext.CALLER_USER_HANDLE));
763
764 // Again broadcast from saveSettingsLocked().
765 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
766 MockUtils.checkIntentAction(
767 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
768 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
769 }
770
771 /**
772 * Test for:
773 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
774 */
775 public void testForceRemoveActiveAdmin() throws Exception {
776 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
777
778 // Add admin.
779 setupPackageInPackageManager(admin1.getPackageName(),
780 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
781 /* appId= */ 10138,
782 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
783 dpm.setActiveAdmin(admin1, /* replace =*/ false);
784 assertTrue(dpm.isAdminActive(admin1));
785
786 // Calling from a non-shell uid should fail with a SecurityException
787 mContext.binder.callingUid = 123456;
788 assertExpectException(SecurityException.class,
789 /* messageRegex =*/ "Non-shell user attempted to call",
790 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
791
792 mContext.binder.callingUid = Process.SHELL_UID;
793 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
794
795 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
796 // Verify
797 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
798 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
799 null, DpmMockContext.CALLER_USER_HANDLE);
800 }
801
Makoto Onukib643fb02015-09-22 15:03:44 -0700802 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100803 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
804 *
805 * Validates that when the password history length is set, it is persisted after rebooting
806 */
807 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
808 int passwordHistoryLength = 2;
809
810 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
811 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
812 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
813
814 // Install admin1 on system user.
815 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
816
817 // Set admin1 to active admin and device owner
818 dpm.setActiveAdmin(admin1, false);
819 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
820
821 // Save password history length
822 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
823
824 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
825
826 initializeDpms();
827 reset(mContext.spiedContext);
828
829 // Password history length should persist after rebooted
830 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
831 }
832
833 /**
834 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000835 *
836 * Validates that when the password for a user changes, the notification broadcast intent
837 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
838 * addition to ones in the original user.
839 */
840 public void testSetActivePasswordState_sendToProfiles() throws Exception {
841 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
842
843 final int MANAGED_PROFILE_USER_ID = 78;
844 final int MANAGED_PROFILE_ADMIN_UID =
845 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
846
Robin Leed2a73ed2016-12-19 09:07:16 +0000847 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
848 mContext.packageName = admin1.getPackageName();
Robin Leed2a73ed2016-12-19 09:07:16 +0000849
850 // Add a managed profile belonging to the system user.
851 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
852
853 // Change the parent user's password.
854 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
855
Eran Messeri6ad0e192019-12-01 20:01:21 +0000856 // The managed profile owner should receive this broadcast.
Robin Leed2a73ed2016-12-19 09:07:16 +0000857 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
858 intent.setComponent(admin1);
859 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
860
861 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
862 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100863 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
864 eq(null),
865 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000866 }
867
868 /**
Rubin Xu19854862019-08-15 16:37:23 +0100869 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000870 *
871 * Validates that when the password for a managed profile changes, the notification broadcast
872 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
873 * its parent.
874 */
875 public void testSetActivePasswordState_notSentToParent() throws Exception {
876 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
877
878 final int MANAGED_PROFILE_USER_ID = 78;
879 final int MANAGED_PROFILE_ADMIN_UID =
880 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
881
Eran Messeri6ad0e192019-12-01 20:01:21 +0000882 // Configure system as having separate profile challenge.
Robin Leed2a73ed2016-12-19 09:07:16 +0000883 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
884 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100885 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000886 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
Robin Leed2a73ed2016-12-19 09:07:16 +0000887
888 // Add a managed profile belonging to the system user.
889 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
890
891 // Change the profile's password.
892 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
893
894 // Both the device owner and the managed profile owner should receive this broadcast.
895 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
896 intent.setComponent(admin1);
897 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
898
899 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
900 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100901 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
902 eq(null),
903 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000904 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
905 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100906 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
907 eq(null),
908 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000909 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100910
Robin Leed2a73ed2016-12-19 09:07:16 +0000911 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000912 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 */
914 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000915 setDeviceOwner();
916
917 // Try to set a profile owner on the same user, which should fail.
918 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
919 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100920 assertExpectException(IllegalStateException.class,
921 /* messageRegex= */ "already has a device owner",
922 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000923
924 // DO admin can't be deactivated.
925 dpm.removeActiveAdmin(admin1);
926 assertTrue(dpm.isAdminActive(admin1));
927
928 // TODO Test getDeviceOwnerName() too. To do so, we need to change
929 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
930 }
931
932 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700933 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800934 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
936 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
937
Makoto Onukid932f762015-09-29 16:53:38 -0700938 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700939 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
940
Makoto Onukid932f762015-09-29 16:53:38 -0700941 // Make sure admin1 is installed on system user.
942 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700943
Makoto Onukic8a5a552015-11-19 14:29:12 -0800944 // Check various get APIs.
945 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
946
Makoto Onukib643fb02015-09-22 15:03:44 -0700947 // DO needs to be an DA.
948 dpm.setActiveAdmin(admin1, /* replace =*/ false);
949
950 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700951 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700952
Makoto Onukic8a5a552015-11-19 14:29:12 -0800953 // getDeviceOwnerComponent should return the admin1 component.
954 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
955 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
956
957 // Check various get APIs.
958 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
959
960 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
961 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
962 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
963 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
964
965 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
966
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000967 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100968 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000969 eq(admin1.getPackageName()));
970
Eran Messeri6ad0e192019-12-01 20:01:21 +0000971 verify(getServices().userManager, times(1)).setUserRestriction(
972 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
973 eq(true), eq(UserHandle.SYSTEM));
974
Makoto Onukib643fb02015-09-22 15:03:44 -0700975 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
976 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
977 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
978
Makoto Onukic8a5a552015-11-19 14:29:12 -0800979 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700980 }
981
Makoto Onukic8a5a552015-11-19 14:29:12 -0800982 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
983 final int origCallingUser = mContext.binder.callingUid;
984 final List origPermissions = new ArrayList(mContext.callerPermissions);
985 mContext.callerPermissions.clear();
986
987 mContext.callerPermissions.add(permission.MANAGE_USERS);
988
989 mContext.binder.callingUid = Process.SYSTEM_UID;
990
991 // TODO Test getDeviceOwnerName() too. To do so, we need to change
992 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
993 if (hasDeviceOwner) {
994 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
995 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
996 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
997
998 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
999 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1000 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1001 } else {
1002 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1003 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1004 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1005
1006 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1007 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1008 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1009 }
1010
1011 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1012 if (hasDeviceOwner) {
1013 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1014 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1015 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1016
1017 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1018 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1019 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1020 } else {
1021 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1022 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1023 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1024
1025 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1026 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1027 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1028 }
1029
1030 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1031 // Still with MANAGE_USERS.
1032 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1033 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1034 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1035
1036 if (hasDeviceOwner) {
1037 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1038 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1039 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1040 } else {
1041 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1042 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1043 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1044 }
1045
1046 mContext.binder.callingUid = Process.SYSTEM_UID;
1047 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1048 // System can still call "OnAnyUser" without MANAGE_USERS.
1049 if (hasDeviceOwner) {
1050 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1051 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1052 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1053
1054 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1055 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1056 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1057 } else {
1058 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1059 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1060 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1061
1062 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1063 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1064 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1065 }
1066
1067 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1068 // Still no MANAGE_USERS.
1069 if (hasDeviceOwner) {
1070 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1071 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1072 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1073 } else {
1074 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1075 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1076 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1077 }
1078
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001079 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1080 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1081 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1082 dpm::getDeviceOwnerComponentOnAnyUser);
1083 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1084 dpm::getDeviceOwnerUserId);
1085 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1086 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001087
1088 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1089 // Still no MANAGE_USERS.
1090 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1091 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1092 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1093
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001094 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1095 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1096 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1097 dpm::getDeviceOwnerComponentOnAnyUser);
1098 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1099 dpm::getDeviceOwnerUserId);
1100 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1101 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001102
1103 // Restore.
1104 mContext.binder.callingUid = origCallingUser;
1105 mContext.callerPermissions.addAll(origPermissions);
1106 }
1107
1108
Makoto Onukib643fb02015-09-22 15:03:44 -07001109 /**
1110 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1111 */
1112 public void testSetDeviceOwner_noSuchPackage() {
1113 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001114 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001115 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1116 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1117
1118 // Call from a process on the system user.
1119 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1120
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001121 assertExpectException(IllegalArgumentException.class,
1122 /* messageRegex= */ "Invalid component",
1123 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001124 }
1125
1126 public void testSetDeviceOwner_failures() throws Exception {
1127 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1128 }
1129
Makoto Onukia52562c2015-10-01 16:12:31 -07001130 public void testClearDeviceOwner() throws Exception {
1131 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001132 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1134 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1135
1136 // Set admin1 as a DA to the secondary user.
1137 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1138
1139 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1140
1141 // Set admin 1 as the DO to the system user.
1142
1143 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1144 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1145 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1146 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1147
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001148 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001149 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001150 eq(admin1.getPackageName()));
1151
Makoto Onukic8a5a552015-11-19 14:29:12 -08001152 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001153
Makoto Onuki90b89652016-01-28 14:44:18 -08001154 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001155 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001156 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001157
1158 assertTrue(dpm.isAdminActive(admin1));
1159 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1160
Makoto Onukia52562c2015-10-01 16:12:31 -07001161 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001162 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001163
1164 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001165 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1166 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001167
1168 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001169 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001170 assertExpectException(IllegalStateException.class,
1171 /* messageRegex= */ "User must be running and unlocked",
1172 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001173
Pavel Grafov75c0a892017-05-18 17:28:27 +01001174 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1175 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001176 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1177
1178 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001179 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001180
Pavel Grafov75c0a892017-05-18 17:28:27 +01001181 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001182 eq(false),
1183 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1184
Pavel Grafov75c0a892017-05-18 17:28:27 +01001185 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnston51419382019-11-26 17:00:10 +00001186 eq(UserHandle.USER_SYSTEM),
Eran Messerice273df2019-12-17 13:14:45 +00001187 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001188 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Makoto Onuki90b89652016-01-28 14:44:18 -08001189
Sudheer Shanka101c3532018-01-08 16:28:42 -08001190 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1191 null, UserHandle.USER_SYSTEM);
1192
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001193 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001194
1195 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1196 // and once for clearing it.
1197 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1198 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1199 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001200 // TODO Check other calls.
1201 }
1202
Pavel Grafov775b26d82019-10-30 13:29:01 +00001203 public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1204 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1205 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1206
1207 // Set admin1 as a DA to the secondary user.
1208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1209 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1210 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1211 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1212
1213 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1214 eq(UserHandle.USER_SYSTEM), eq(false));
1215
1216 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1217
1218 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1219 eq(UserHandle.USER_SYSTEM), eq(true));
1220 }
1221
1222 public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1223 setAsProfileOwner(admin1);
1224
1225 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1226 eq(DpmMockContext.CALLER_USER_HANDLE), eq(false));
1227
1228 dpm.clearProfileOwner(admin1);
1229
1230 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1231 eq(DpmMockContext.CALLER_USER_HANDLE), eq(true));
1232 }
1233
Makoto Onukia52562c2015-10-01 16:12:31 -07001234 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1235 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001236 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001237 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1238 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1239
1240 // Set admin1 as a DA to the secondary user.
1241 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1242
1243 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1244
1245 // Set admin 1 as the DO to the system user.
1246
1247 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1248 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1249 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1250 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1251
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001252 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001253 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001254 eq(admin1.getPackageName()));
1255
Makoto Onukic8a5a552015-11-19 14:29:12 -08001256 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001257
1258 // Now call clear from the secondary user, which should throw.
1259 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1260
1261 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001262 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001263 eq(admin1.getPackageName()),
1264 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001265 assertExpectException(SecurityException.class,
1266 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1267 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001268
Makoto Onukic8a5a552015-11-19 14:29:12 -08001269 // DO shouldn't be removed.
1270 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001271 }
1272
Alex Johnston63220932019-09-26 10:10:51 +01001273 /**
1274 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1275 *
1276 * Validates that when the device owner is removed, the reset password token is cleared
1277 */
1278 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1279 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1280 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1281 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1282
1283 // Install admin1 on system user
1284 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1285
1286 // Set admin1 to active admin and device owner
1287 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1288 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1289
1290 // Add reset password token
1291 final long handle = 12000;
1292 final byte[] token = new byte[32];
1293 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1294 nullable(EscrowTokenStateChangeCallback.class)))
1295 .thenReturn(handle);
1296 assertTrue(dpm.setResetPasswordToken(admin1, token));
1297
1298 // Assert reset password token is active
1299 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1300 eq(UserHandle.USER_SYSTEM)))
1301 .thenReturn(true);
1302 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1303
1304 // Remove the device owner
1305 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1306
1307 // Verify password reset password token was removed
1308 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1309 eq(UserHandle.USER_SYSTEM));
1310 }
1311
Makoto Onukib643fb02015-09-22 15:03:44 -07001312 public void testSetProfileOwner() throws Exception {
1313 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001314
Makoto Onuki90b89652016-01-28 14:44:18 -08001315 // PO admin can't be deactivated.
1316 dpm.removeActiveAdmin(admin1);
1317 assertTrue(dpm.isAdminActive(admin1));
1318
Makoto Onuki803d6752015-10-30 12:58:39 -07001319 // Try setting DO on the same user, which should fail.
1320 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001321 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1322 runAsCaller(mServiceContext, dpms, dpm -> {
1323 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001324 assertExpectException(IllegalStateException.class,
1325 /* messageRegex= */ "already has a profile owner",
1326 () -> dpm.setDeviceOwner(admin2, "owner-name",
1327 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001328 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001329 }
1330
Makoto Onuki90b89652016-01-28 14:44:18 -08001331 public void testClearProfileOwner() throws Exception {
1332 setAsProfileOwner(admin1);
1333
1334 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1335
1336 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1337 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1338
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001339 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001340 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001341 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001342 assertExpectException(IllegalStateException.class,
1343 /* messageRegex= */ "User must be running and unlocked",
1344 () -> dpm.clearProfileOwner(admin1));
1345
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001346 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001347 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001348 dpm.clearProfileOwner(admin1);
1349
1350 // Check
1351 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001352 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001353 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1354 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001355 }
1356
Makoto Onukib643fb02015-09-22 15:03:44 -07001357 public void testSetProfileOwner_failures() throws Exception {
1358 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1359 }
1360
Makoto Onukia52562c2015-10-01 16:12:31 -07001361 public void testGetDeviceOwnerAdminLocked() throws Exception {
1362 checkDeviceOwnerWithMultipleDeviceAdmins();
1363 }
1364
1365 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1366 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1367 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1368 // make sure it gets the right component from the right user.
1369
1370 final int ANOTHER_USER_ID = 100;
1371 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1372
Alex Johnston755e3772019-11-29 03:27:22 +00001373 getServices().addUser(ANOTHER_USER_ID, 0, ""); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001374
1375 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001376 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001377 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1378 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1379
1380 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1381
Pavel Grafov75c0a892017-05-18 17:28:27 +01001382 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001383
Makoto Onukia52562c2015-10-01 16:12:31 -07001384 // Make sure the admin packge is installed to each user.
1385 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1386 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1387
1388 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1389 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1390
1391 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1392
1393
1394 // Set active admins to the users.
1395 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1396 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1397
1398 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1399 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1400
1401 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1402
1403 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001404 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001405 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1406
Makoto Onukic8a5a552015-11-19 14:29:12 -08001407 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001408
1409 // Then check getDeviceOwnerAdminLocked().
1410 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1411 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1412 }
1413
1414 /**
1415 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001416 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1417 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001418 *
1419 * We didn't use to persist the DO component class name, but now we do, and the above method
1420 * finds the right component from a package name upon migration.
1421 */
1422 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001423 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001424 checkDeviceOwnerWithMultipleDeviceAdmins();
1425
1426 // Overwrite the device owner setting and clears the clas name.
1427 dpms.mOwners.setDeviceOwner(
1428 new ComponentName(admin2.getPackageName(), ""),
1429 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1430 dpms.mOwners.writeDeviceOwner();
1431
1432 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001433 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001434
1435 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001436 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001437 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001438 initializeDpms();
1439
1440 // Now the DO component name is a full name.
1441 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1442 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001443 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001444 }
1445
Makoto Onukib643fb02015-09-22 15:03:44 -07001446 public void testSetGetApplicationRestriction() {
1447 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001448 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001449
1450 {
1451 Bundle rest = new Bundle();
1452 rest.putString("KEY_STRING", "Foo1");
1453 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1454 }
1455
1456 {
1457 Bundle rest = new Bundle();
1458 rest.putString("KEY_STRING", "Foo2");
1459 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1460 }
1461
1462 {
1463 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1464 assertNotNull(returned);
1465 assertEquals(returned.size(), 1);
1466 assertEquals(returned.get("KEY_STRING"), "Foo1");
1467 }
1468
1469 {
1470 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1471 assertNotNull(returned);
1472 assertEquals(returned.size(), 1);
1473 assertEquals(returned.get("KEY_STRING"), "Foo2");
1474 }
1475
1476 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1477 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1478 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001479
Edman Anjosf9946772016-11-28 16:35:15 +01001480 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001481 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1482 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001483 *
1484 * @param packageName the name of the package to be setup
1485 * @param appId the application ID to be given to the package
1486 * @return the UID of the package as known by the mock package manager
1487 */
1488 private int setupPackageInPackageManager(final String packageName, final int appId)
1489 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001490 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001491 ApplicationInfo.FLAG_HAS_CODE);
1492 }
1493
1494 /**
1495 * Setup a package in the package manager mock. Useful for faking installed applications.
1496 *
1497 * @param packageName the name of the package to be setup
1498 * @param userId the user id where the package will be "installed"
1499 * @param appId the application ID to be given to the package
1500 * @param flags flags to set in the ApplicationInfo for this package
1501 * @return the UID of the package as known by the mock package manager
1502 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001503 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1504 int flags) throws Exception {
1505 final int uid = UserHandle.getUid(userId, appId);
1506 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001507 final PackageInfo pi = new PackageInfo();
1508 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001509 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001510 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001511 eq(packageName),
1512 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001513 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001514 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001515 eq(packageName),
1516 anyInt(),
1517 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001518 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001519 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001520 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001521 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001522 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001523 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001524 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001525 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001526 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001527 return uid;
1528 }
1529
Robin Lee7f5c91c2017-02-08 21:27:02 +00001530 public void testCertificateDisclosure() throws Exception {
1531 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1532 final UserHandle user = UserHandle.of(userId);
1533
1534 mContext.applicationInfo = new ApplicationInfo();
1535 mContext.callerPermissions.add(permission.MANAGE_USERS);
1536 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001537 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001538 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1539
Robin Leeabaa0692017-02-20 20:54:22 +00001540 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1541 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001542
1543 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1544 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1545
1546 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001547 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001548 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001549 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001550 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001551 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001552 .cancelAsUser(anyString(), anyInt(), eq(user));
1553
1554 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001555 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001556 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001557 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1558 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001559 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001560 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001561 .notifyAsUser(anyString(), anyInt(), argThat(
1562 new BaseMatcher<Notification>() {
1563 @Override
1564 public boolean matches(Object item) {
1565 final Notification noti = (Notification) item;
1566 return TEST_STRING.equals(
1567 noti.extras.getString(Notification.EXTRA_TITLE));
1568 }
1569 @Override
1570 public void describeTo(Description description) {
1571 description.appendText(
1572 "Notification{title=\"" + TEST_STRING + "\"}");
1573 }
1574 }), eq(user));
1575 }
1576
Edman Anjosf9946772016-11-28 16:35:15 +01001577 /**
1578 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1579 * privileges can acually be exercised by a delegate are not covered here.
1580 */
1581 public void testDelegation() throws Exception {
1582 setAsProfileOwner(admin1);
1583
1584 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1585
1586 // Given two packages
1587 final String CERT_DELEGATE = "com.delegate.certs";
1588 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1589 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1590 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1591 20989);
1592
1593 // On delegation
1594 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1595 mContext.packageName = admin1.getPackageName();
1596 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1597 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1598
1599 // DPMS correctly stores and retrieves the delegates
1600 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1601 assertEquals(2, policy.mDelegationMap.size());
1602 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1603 DELEGATION_CERT_INSTALL);
1604 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1605 DELEGATION_CERT_INSTALL);
1606 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1607 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1608 DELEGATION_APP_RESTRICTIONS);
1609 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1610 DELEGATION_APP_RESTRICTIONS);
1611 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1612
1613 // On calling install certificate APIs from an unauthorized process
1614 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1615 mContext.packageName = RESTRICTIONS_DELEGATE;
1616
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001617 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1618 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001619
1620 // On calling install certificate APIs from an authorized process
1621 mContext.binder.callingUid = CERT_DELEGATE_UID;
1622 mContext.packageName = CERT_DELEGATE;
1623
1624 // DPMS executes without a SecurityException
1625 try {
1626 dpm.installCaCert(null, null);
1627 } catch (SecurityException unexpected) {
1628 fail("Threw SecurityException on authorized access");
1629 } catch (NullPointerException expected) {
1630 }
1631
1632 // On removing a delegate
1633 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1634 mContext.packageName = admin1.getPackageName();
1635 dpm.setCertInstallerPackage(admin1, null);
1636
1637 // DPMS does not allow access to ex-delegate
1638 mContext.binder.callingUid = CERT_DELEGATE_UID;
1639 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001640 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1641 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001642
1643 // But still allows access to other existing delegates
1644 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1645 mContext.packageName = RESTRICTIONS_DELEGATE;
1646 try {
1647 dpm.getApplicationRestrictions(null, "pkg");
1648 } catch (SecurityException expected) {
1649 fail("Threw SecurityException on authorized access");
1650 }
1651 }
1652
Esteban Talaverabf60f722015-12-10 16:26:44 +00001653 public void testApplicationRestrictionsManagingApp() throws Exception {
1654 setAsProfileOwner(admin1);
1655
Rubin Xued1928a2016-02-11 17:23:06 +00001656 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001657 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001658 final String nonDelegateExceptionMessageRegex =
1659 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001660 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001661 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1662 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001663
Esteban Talaverabf60f722015-12-10 16:26:44 +00001664 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1665 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001666 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1667 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001668 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001669 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001670 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001671 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1672 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001673
1674 // Check via the profile owner that no restrictions were set.
1675 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001676 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001677 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1678
Rubin Xued1928a2016-02-11 17:23:06 +00001679 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001680 assertExpectException(PackageManager.NameNotFoundException.class,
1681 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1682 () -> dpm.setApplicationRestrictionsManagingPackage(
1683 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001684
Esteban Talaverabf60f722015-12-10 16:26:44 +00001685 // Let appRestrictionsManagerPackage manage app restrictions
1686 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1687 assertEquals(appRestrictionsManagerPackage,
1688 dpm.getApplicationRestrictionsManagingPackage(admin1));
1689
1690 // Now that package should be able to set and retrieve app restrictions.
1691 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001692 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001693 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1694 dpm.setApplicationRestrictions(null, "pkg1", rest);
1695 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1696 assertEquals(1, returned.size(), 1);
1697 assertEquals("Foo1", returned.get("KEY_STRING"));
1698
1699 // The same app running on a separate user shouldn't be able to manage app restrictions.
1700 mContext.binder.callingUid = UserHandle.getUid(
1701 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1702 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001703 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1704 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001705
1706 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1707 // too.
1708 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001709 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001710 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1711 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1712 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1713
1714 // Removing the ability for the package to manage app restrictions.
1715 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1716 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1717 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001718 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001719 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001720 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1721 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001722 }
1723
Makoto Onukia4f11972015-10-01 13:19:58 -07001724 public void testSetUserRestriction_asDo() throws Exception {
1725 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001726 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001727 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1728 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1729
1730 // First, set DO.
1731
1732 // Call from a process on the system user.
1733 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1734
1735 // Make sure admin1 is installed on system user.
1736 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001737
1738 // Call.
1739 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001740 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001741 UserHandle.USER_SYSTEM));
1742
Esteban Talavera548a04b2016-12-20 15:22:30 +00001743 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001744 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745
1746 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001747 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001748 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001749 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001750 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001751 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001752
Makoto Onukia4f11972015-10-01 13:19:58 -07001753 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001754 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001755 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001756 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1757 UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001758 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001759 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001760
Makoto Onuki068c54a2015-10-13 14:34:03 -07001761 DpmTestUtils.assertRestrictions(
1762 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001764 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1765 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001766 DpmTestUtils.assertRestrictions(
1767 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001769 dpm.getUserRestrictions(admin1)
1770 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001771
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001772 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001773 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001774 eq(UserHandle.USER_SYSTEM),
1775 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001776 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001777 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001778
Makoto Onuki068c54a2015-10-13 14:34:03 -07001779 DpmTestUtils.assertRestrictions(
1780 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1781 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1782 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001783 DpmTestUtils.assertRestrictions(
1784 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1785 dpm.getUserRestrictions(admin1)
1786 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001787
1788 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001789 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001790 eq(UserHandle.USER_SYSTEM),
1791 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001792 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001793 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001794
Esteban Talavera548a04b2016-12-20 15:22:30 +00001795 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001796
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001797 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1798 // DO sets them, the scope is global.
1799 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001800 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001801 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001802 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001805 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001806 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001808
1809 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1810 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001811 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001812
1813 // More tests.
1814 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001815 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001816 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001817 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001818 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001819 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001820
1821 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001822 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001823 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001824 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001825 UserManager.DISALLOW_ADD_USER),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001826 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001827 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828
1829 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001830 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001831 eq(UserHandle.USER_SYSTEM),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001832 // DISALLOW_CAMERA will be applied globally.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001833 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001834 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_CAMERA),
1835 eq(UserManagerInternal.OWNER_TYPE_DEVICE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001836 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001837 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001838
Eric Sandnessca5969d2018-08-10 13:28:46 +01001839 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1840 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1841 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001842
Eric Sandnessca5969d2018-08-10 13:28:46 +01001843 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1844 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001845
Eric Sandnessca5969d2018-08-10 13:28:46 +01001846 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1847 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1848 () -> dpm.setCameraDisabled(admin1, true));
1849 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1850
1851 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1852 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1853 () -> dpm.setKeyguardDisabledFeatures(admin1,
1854 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1855 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1856
1857 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1858 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1859 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1860 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1861
1862 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1863 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1864 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1865 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001866 }
1867
1868 public void testSetUserRestriction_asPo() {
1869 setAsProfileOwner(admin1);
1870
Makoto Onuki068c54a2015-10-13 14:34:03 -07001871 DpmTestUtils.assertRestrictions(
1872 DpmTestUtils.newRestrictions(),
1873 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1874 .ensureUserRestrictions()
1875 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001876
1877 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001878 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001879 eq(DpmMockContext.CALLER_USER_HANDLE),
1880 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001881 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001883
Makoto Onukia4f11972015-10-01 13:19:58 -07001884 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001885 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001886 eq(DpmMockContext.CALLER_USER_HANDLE),
1887 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1888 UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001889 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001890 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001891
Makoto Onuki068c54a2015-10-13 14:34:03 -07001892 DpmTestUtils.assertRestrictions(
1893 DpmTestUtils.newRestrictions(
1894 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1895 UserManager.DISALLOW_OUTGOING_CALLS
1896 ),
1897 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1898 .ensureUserRestrictions()
1899 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001900 DpmTestUtils.assertRestrictions(
1901 DpmTestUtils.newRestrictions(
1902 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1903 UserManager.DISALLOW_OUTGOING_CALLS
1904 ),
1905 dpm.getUserRestrictions(admin1)
1906 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001907
1908 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001909 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001910 eq(DpmMockContext.CALLER_USER_HANDLE),
1911 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001912 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001913 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001914
1915 DpmTestUtils.assertRestrictions(
1916 DpmTestUtils.newRestrictions(
1917 UserManager.DISALLOW_OUTGOING_CALLS
1918 ),
1919 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1920 .ensureUserRestrictions()
1921 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001922 DpmTestUtils.assertRestrictions(
1923 DpmTestUtils.newRestrictions(
1924 UserManager.DISALLOW_OUTGOING_CALLS
1925 ),
1926 dpm.getUserRestrictions(admin1)
1927 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001928
1929 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001930 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001931 eq(DpmMockContext.CALLER_USER_HANDLE),
1932 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001933 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001934 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001935
Makoto Onuki068c54a2015-10-13 14:34:03 -07001936 DpmTestUtils.assertRestrictions(
1937 DpmTestUtils.newRestrictions(),
1938 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1939 .ensureUserRestrictions()
1940 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001941 DpmTestUtils.assertRestrictions(
1942 DpmTestUtils.newRestrictions(),
1943 dpm.getUserRestrictions(admin1)
1944 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001945
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001946 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1947 // though when DO sets them they'll be applied globally.
1948 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001949 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001950 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001951 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001952 eq(DpmMockContext.CALLER_USER_HANDLE),
1953 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1954 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001955 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001956 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001957
1958 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001959 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001960 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001961 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001962 UserManager.DISALLOW_UNMUTE_MICROPHONE, UserManager.DISALLOW_CAMERA),
1963 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001964 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001965
Makoto Onukia4f11972015-10-01 13:19:58 -07001966 // TODO Make sure restrictions are written to the file.
1967 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001968
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001969 private static final Set<String> PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS =
1970 Sets.newSet(
1971 UserManager.DISALLOW_CONFIG_DATE_TIME,
1972 UserManager.DISALLOW_ADD_USER,
1973 UserManager.DISALLOW_BLUETOOTH,
1974 UserManager.DISALLOW_BLUETOOTH_SHARING,
1975 UserManager.DISALLOW_CONFIG_BLUETOOTH,
1976 UserManager.DISALLOW_CONFIG_CELL_BROADCASTS,
1977 UserManager.DISALLOW_CONFIG_LOCATION,
1978 UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
1979 UserManager.DISALLOW_CONFIG_PRIVATE_DNS,
1980 UserManager.DISALLOW_CONFIG_TETHERING,
1981 UserManager.DISALLOW_CONFIG_WIFI,
1982 UserManager.DISALLOW_CONTENT_CAPTURE,
1983 UserManager.DISALLOW_CONTENT_SUGGESTIONS,
1984 UserManager.DISALLOW_DATA_ROAMING,
1985 UserManager.DISALLOW_DEBUGGING_FEATURES,
1986 UserManager.DISALLOW_SAFE_BOOT,
1987 UserManager.DISALLOW_SHARE_LOCATION,
1988 UserManager.DISALLOW_SMS,
1989 UserManager.DISALLOW_USB_FILE_TRANSFER
1990 );
1991
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001992 public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00001993 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
1994 final int MANAGED_PROFILE_ADMIN_UID =
1995 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
1996 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001997
Alex Johnston755e3772019-11-29 03:27:22 +00001998 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
1999 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002000
Alex Johnston755e3772019-11-29 03:27:22 +00002001 when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2002 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002003
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002004 for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
2005 addAndRemoveUserRestrictionOnParentDpm(restriction);
2006 }
Alex Johnston51419382019-11-26 17:00:10 +00002007
Alex Johnston755e3772019-11-29 03:27:22 +00002008 parentDpm.setCameraDisabled(admin1, true);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002009 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnston51419382019-11-26 17:00:10 +00002010 eq(MANAGED_PROFILE_USER_ID),
Alex Johnston755e3772019-11-29 03:27:22 +00002011 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002012 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2013 reset(getServices().userManagerInternal);
2014
Alex Johnston755e3772019-11-29 03:27:22 +00002015 parentDpm.setCameraDisabled(admin1, false);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002016 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnston51419382019-11-26 17:00:10 +00002017 eq(MANAGED_PROFILE_USER_ID),
Alex Johnston755e3772019-11-29 03:27:22 +00002018 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002019 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2020 reset(getServices().userManagerInternal);
2021 }
Esteban Talavera548a04b2016-12-20 15:22:30 +00002022
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002023 private void addAndRemoveUserRestrictionOnParentDpm(String restriction) {
2024 parentDpm.addUserRestriction(admin1, restriction);
2025 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2026 eq(DpmMockContext.CALLER_USER_HANDLE),
2027 MockUtils.checkUserRestrictions(restriction),
2028 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2029 parentDpm.clearUserRestriction(admin1, restriction);
2030 DpmTestUtils.assertRestrictions(
2031 DpmTestUtils.newRestrictions(),
2032 parentDpm.getUserRestrictions(admin1)
2033 );
2034 reset(getServices().userManagerInternal);
2035 }
2036
Eran Messerice273df2019-12-17 13:14:45 +00002037 public void testNoDefaultEnabledUserRestrictions() throws Exception {
Esteban Talavera548a04b2016-12-20 15:22:30 +00002038 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2039 mContext.callerPermissions.add(permission.MANAGE_USERS);
2040 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2041 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2042
2043 // First, set DO.
2044
2045 // Call from a process on the system user.
2046 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2047
2048 // Make sure admin1 is installed on system user.
2049 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2050
2051 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2052 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
2053 UserHandle.USER_SYSTEM));
2054
Esteban Talavera548a04b2016-12-20 15:22:30 +00002055 assertNoDeviceOwnerRestrictions();
2056
Pavel Grafov75c0a892017-05-18 17:28:27 +01002057 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002058
Eran Messeri6ad0e192019-12-01 20:01:21 +00002059 // Ensure the DISALLOW_REMOVE_MANAGED_PROFILES restriction doesn't show up as a
2060 // restriction to the device owner.
2061 dpm.addUserRestriction(admin1, UserManager.DISALLOW_REMOVE_MANAGED_PROFILE);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002062 assertNoDeviceOwnerRestrictions();
Esteban Talavera548a04b2016-12-20 15:22:30 +00002063 }
2064
2065 private void assertNoDeviceOwnerRestrictions() {
2066 DpmTestUtils.assertRestrictions(
2067 DpmTestUtils.newRestrictions(),
2068 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2069 );
2070 DpmTestUtils.assertRestrictions(
2071 DpmTestUtils.newRestrictions(),
2072 dpm.getUserRestrictions(admin1)
2073 );
2074 }
2075
Alex Johnston011f5c62019-12-18 17:05:57 +00002076 public void testSetFactoryResetProtectionPolicyWithDO() throws Exception {
2077 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2078 setupDeviceOwner();
2079
2080 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2081 DpmMockContext.CALLER_UID);
2082
2083 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2084 .setFactoryResetProtectionAccounts(new ArrayList<>())
2085 .setFactoryResetProtectionDisabled(true)
2086 .build();
2087 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2088
2089 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2090 assertThat(result).isEqualTo(policy);
2091 assertPoliciesAreEqual(policy, result);
2092
2093 verify(mContext.spiedContext).sendBroadcastAsUser(
2094 MockUtils.checkIntentAction(
2095 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2096 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2097 }
2098
2099 public void testSetFactoryResetProtectionPolicyFailWithPO() throws Exception {
2100 setupProfileOwner();
2101
2102 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2103 .setFactoryResetProtectionDisabled(true)
2104 .build();
2105
2106 assertExpectException(SecurityException.class, null,
2107 () -> dpm.setFactoryResetProtectionPolicy(admin1, policy));
2108 }
2109
2110 public void testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice()
2111 throws Exception {
2112 setupProfileOwner();
2113 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2114
2115 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2116 DpmMockContext.CALLER_UID);
2117
2118 List<String> accounts = new ArrayList<>();
2119 accounts.add("Account 1");
2120 accounts.add("Account 2");
2121
2122 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2123 .setFactoryResetProtectionAccounts(accounts)
2124 .build();
2125
2126 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2127
2128 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2129 assertThat(result).isEqualTo(policy);
2130 assertPoliciesAreEqual(policy, result);
2131
2132 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
2133 MockUtils.checkIntentAction(
2134 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
2135 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2136 verify(mContext.spiedContext).sendBroadcastAsUser(
2137 MockUtils.checkIntentAction(
2138 DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED),
2139 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2140 verify(mContext.spiedContext).sendBroadcastAsUser(
2141 MockUtils.checkIntentAction(
2142 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2143 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2144 }
2145
2146 public void testGetFactoryResetProtectionPolicyWithFrpManagementAgent()
2147 throws Exception {
2148 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2149 setupDeviceOwner();
2150 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2151 DpmMockContext.CALLER_UID);
2152
2153 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2154 .setFactoryResetProtectionAccounts(new ArrayList<>())
2155 .setFactoryResetProtectionDisabled(true)
2156 .build();
2157
2158 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2159
2160 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2161 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2162 dpm.setActiveAdmin(admin1, /*replace=*/ false);
2163 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(null);
2164 assertThat(result).isEqualTo(policy);
2165 assertPoliciesAreEqual(policy, result);
2166
2167 verify(mContext.spiedContext).sendBroadcastAsUser(
2168 MockUtils.checkIntentAction(
2169 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2170 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2171 }
2172
2173 private void assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy,
2174 FactoryResetProtectionPolicy actualPolicy) {
2175 assertThat(actualPolicy.isFactoryResetProtectionDisabled()).isEqualTo(
2176 expectedPolicy.isFactoryResetProtectionDisabled());
2177 assertAccountsAreEqual(expectedPolicy.getFactoryResetProtectionAccounts(),
2178 actualPolicy.getFactoryResetProtectionAccounts());
2179 }
2180
2181 private void assertAccountsAreEqual(List<String> expectedAccounts,
2182 List<String> actualAccounts) {
2183 assertThat(actualAccounts).containsExactlyElementsIn(expectedAccounts);
2184 }
2185
Alex Johnstona552dd62020-01-17 17:05:25 +00002186 public void testSetApplicationHiddenWithDO() throws Exception {
2187 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2188 setupDeviceOwner();
2189 mContext.packageName = admin1.getPackageName();
2190 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2191
2192 String packageName = "com.google.android.test";
2193
2194 dpm.setApplicationHidden(admin1, packageName, true);
2195 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2196 true, UserHandle.USER_SYSTEM);
2197
2198 dpm.setApplicationHidden(admin1, packageName, false);
2199 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2200 false, UserHandle.USER_SYSTEM);
2201
2202 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2203 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
2204 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2205 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2206 UserHandle.USER_SYSTEM);
2207 }
2208
2209 public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception {
2210 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
2211 final int MANAGED_PROFILE_ADMIN_UID =
2212 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2213 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2214
2215 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2216 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2217 mContext.packageName = admin1.getPackageName();
2218 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2219
2220 String packageName = "com.google.android.test";
2221
2222 PackageInfo packageInfo = new PackageInfo();
2223 packageInfo.applicationInfo = new ApplicationInfo();
2224 packageInfo.applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
2225 when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2226 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
2227 when(getServices().ipackageManager.getPackageInfo(packageName,
2228 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM)).thenReturn(
2229 packageInfo);
2230 when(getServices().ipackageManager.getPackageInfo(packageName,
2231 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2232 UserHandle.USER_SYSTEM)).thenReturn(packageInfo);
2233
2234 parentDpm.setApplicationHidden(admin1, packageName, true);
2235 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2236 true, UserHandle.USER_SYSTEM);
2237
2238 parentDpm.setApplicationHidden(admin1, packageName, false);
2239 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2240 false, UserHandle.USER_SYSTEM);
2241 }
2242
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002243 public void testGetMacAddress() throws Exception {
2244 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2245 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2246 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2247
2248 // In this test, change the caller user to "system".
2249 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2250
2251 // Make sure admin1 is installed on system user.
2252 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2253
2254 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002255 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2256 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002257
2258 // DO needs to be an DA.
2259 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2260 assertTrue(dpm.isAdminActive(admin1));
2261
2262 // Test 2. Caller has DA, but not DO.
Eran Messeri6ba10db2019-12-04 15:53:27 +00002263 assertExpectException(SecurityException.class,
2264 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002265 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002266
2267 // Test 3. Caller has PO, but not DO.
2268 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Eran Messeri6ba10db2019-12-04 15:53:27 +00002269 assertExpectException(SecurityException.class,
2270 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002271 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002272
2273 // Remove PO.
2274 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002275 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002276 // Test 4, Caller is DO now.
2277 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2278
xshu425b9a62018-12-13 14:18:18 -08002279 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002280 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002281
xshu425b9a62018-12-13 14:18:18 -08002282 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2283 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002284 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002285
2286 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002287 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2288 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002289 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002290 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002291
Eran Messeri6ba10db2019-12-04 15:53:27 +00002292 public void testGetMacAddressByOrgOwnedPO() throws Exception {
2293 setupProfileOwner();
2294 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2295
2296 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2297 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
2298 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
2299 }
2300
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002301 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002302 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2303 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2304
2305 // In this test, change the caller user to "system".
2306 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2307
2308 // Make sure admin1 is installed on system user.
2309 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2310
2311 // Set admin1 as DA.
2312 dpm.setActiveAdmin(admin1, false);
2313 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002314 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2315 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002316
2317 // Set admin1 as PO.
2318 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002319 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2320 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002321
2322 // Remove PO and add DO.
2323 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002324 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002325 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2326
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002327 // admin1 is DO.
2328 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002329 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002330 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002331 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2332 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002333
2334 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002335 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002336 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002337 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2338 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002339
2340 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002341 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002342 dpm.reboot(admin1);
2343 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002344
2345 public void testSetGetSupportText() {
2346 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2347 dpm.setActiveAdmin(admin1, true);
2348 dpm.setActiveAdmin(admin2, true);
2349 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2350
2351 // Null default support messages.
2352 {
2353 assertNull(dpm.getLongSupportMessage(admin1));
2354 assertNull(dpm.getShortSupportMessage(admin1));
2355 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2356 assertNull(dpm.getShortSupportMessageForUser(admin1,
2357 DpmMockContext.CALLER_USER_HANDLE));
2358 assertNull(dpm.getLongSupportMessageForUser(admin1,
2359 DpmMockContext.CALLER_USER_HANDLE));
2360 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2361 }
2362
2363 // Only system can call the per user versions.
2364 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002365 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2366 () -> dpm.getShortSupportMessageForUser(admin1,
2367 DpmMockContext.CALLER_USER_HANDLE));
2368 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2369 () -> dpm.getLongSupportMessageForUser(admin1,
2370 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002371 }
2372
2373 // Can't set message for admin in another uid.
2374 {
2375 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002376 assertExpectException(SecurityException.class,
2377 /* messageRegex= */ "is not owned by uid",
2378 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002379 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2380 }
2381
2382 // Set/Get short returns what it sets and other admins text isn't changed.
2383 {
2384 final String supportText = "Some text to test with.";
2385 dpm.setShortSupportMessage(admin1, supportText);
2386 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2387 assertNull(dpm.getLongSupportMessage(admin1));
2388 assertNull(dpm.getShortSupportMessage(admin2));
2389
2390 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2391 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2392 DpmMockContext.CALLER_USER_HANDLE));
2393 assertNull(dpm.getShortSupportMessageForUser(admin2,
2394 DpmMockContext.CALLER_USER_HANDLE));
2395 assertNull(dpm.getLongSupportMessageForUser(admin1,
2396 DpmMockContext.CALLER_USER_HANDLE));
2397 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2398
2399 dpm.setShortSupportMessage(admin1, null);
2400 assertNull(dpm.getShortSupportMessage(admin1));
2401 }
2402
2403 // Set/Get long returns what it sets and other admins text isn't changed.
2404 {
2405 final String supportText = "Some text to test with.\nWith more text.";
2406 dpm.setLongSupportMessage(admin1, supportText);
2407 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2408 assertNull(dpm.getShortSupportMessage(admin1));
2409 assertNull(dpm.getLongSupportMessage(admin2));
2410
2411 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2412 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2413 DpmMockContext.CALLER_USER_HANDLE));
2414 assertNull(dpm.getLongSupportMessageForUser(admin2,
2415 DpmMockContext.CALLER_USER_HANDLE));
2416 assertNull(dpm.getShortSupportMessageForUser(admin1,
2417 DpmMockContext.CALLER_USER_HANDLE));
2418 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2419
2420 dpm.setLongSupportMessage(admin1, null);
2421 assertNull(dpm.getLongSupportMessage(admin1));
2422 }
2423 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002424
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002425 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002426 setAsProfileOwner(admin1);
2427
2428 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002429 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002430
2431 // Setup
2432 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2433 final String package1 = "com.example.one";
2434 final String package2 = "com.example.two";
2435 pkgsToRestrict.add(package1);
2436 pkgsToRestrict.add(package2);
2437 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2438 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002439 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002440
2441 // Verify
2442 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002443 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002444 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2445 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2446 eq(DpmMockContext.CALLER_USER_HANDLE));
2447
2448 // Setup
2449 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002450 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002451
2452 // Verify
2453 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002454 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002455 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2456 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2457 eq(DpmMockContext.CALLER_USER_HANDLE));
2458 }
2459
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002460 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002461 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2462 dpm.setActiveAdmin(admin1, true);
2463 assertTrue(dpm.isAdminActive(admin1));
2464 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2465
2466 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002467 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002468 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002469 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002470 }
2471
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002472 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002473 setAsProfileOwner(admin1);
2474
2475 // Setup
2476 final ArrayList<String> emptyList = new ArrayList<>();
2477 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2478 final String package1 = "com.example.one";
2479 final String package2 = "com.example.two";
2480 final String package3 = "com.example.three";
2481 pkgsToRestrict.add(package1);
2482 pkgsToRestrict.add(package2);
2483 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2484 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002485 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002486
2487 // Verify
2488 assertEquals(emptyList, excludedPkgs);
2489 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2490 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002491 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002492 DpmMockContext.CALLER_USER_HANDLE));
2493 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002494 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002495 DpmMockContext.CALLER_USER_HANDLE));
2496 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002497 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002498 DpmMockContext.CALLER_USER_HANDLE));
2499 }
2500
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002501 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002502 setAsProfileOwner(admin1);
2503 assertExpectException(SecurityException.class,
2504 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002505 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002506 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2507 dpm.clearProfileOwner(admin1);
2508
2509 setDeviceOwner();
2510 assertExpectException(SecurityException.class,
2511 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002512 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002513 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2514 clearDeviceOwner();
2515 }
2516
phweiss73145f42017-01-17 19:06:38 +01002517 public void testCreateAdminSupportIntent() throws Exception {
2518 // Setup device owner.
2519 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2520 setupDeviceOwner();
2521
2522 // Nonexisting permission returns null
2523 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2524 assertNull(intent);
2525
2526 // Existing permission that is not set returns null
2527 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2528 assertNull(intent);
2529
2530 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002531 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002532 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2533 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2534 .thenReturn(true);
2535 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2536 assertNull(intent);
2537
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002538 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2539 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2540 new UserManager.EnforcingUser(
2541 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2542 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002543 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002544 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002545 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2546 assertNotNull(intent);
2547 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2548 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2549 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002550 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002551 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2552 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2553
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002554 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2555 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002556
2557 // Camera is not disabled
2558 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2559 assertNull(intent);
2560
2561 // Camera is disabled
2562 dpm.setCameraDisabled(admin1, true);
2563 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2564 assertNotNull(intent);
2565 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2566 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2567
2568 // Screen capture is not disabled
2569 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2570 assertNull(intent);
2571
2572 // Screen capture is disabled
2573 dpm.setScreenCaptureDisabled(admin1, true);
2574 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2575 assertNotNull(intent);
2576 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2577 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2578
2579 // Same checks for different user
2580 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2581 // Camera should be disabled by device owner
2582 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2583 assertNotNull(intent);
2584 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2585 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2586 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2587 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2588 // ScreenCapture should not be disabled by device owner
2589 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2590 assertNull(intent);
2591 }
2592
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002593 /**
2594 * Test for:
2595 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002596 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002597 * {@link DevicePolicyManager#isAffiliatedUser}
2598 */
2599 public void testUserAffiliation() throws Exception {
2600 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2601 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2602 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2603
2604 // Check that the system user is unaffiliated.
2605 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2606 assertFalse(dpm.isAffiliatedUser());
2607
2608 // Set a device owner on the system user. Check that the system user becomes affiliated.
2609 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2610 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2611 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2612 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002613 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002614
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002615 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002616 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2617 setAsProfileOwner(admin2);
2618 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002619 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002620
2621 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2622 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002623 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002624 userAffiliationIds.add("red");
2625 userAffiliationIds.add("green");
2626 userAffiliationIds.add("blue");
2627 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002628 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002629 assertFalse(dpm.isAffiliatedUser());
2630
2631 // Have the device owner specify a set of affiliation ids that do not intersect with those
2632 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002633 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002634 deviceAffiliationIds.add("cyan");
2635 deviceAffiliationIds.add("yellow");
2636 deviceAffiliationIds.add("magenta");
2637 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2638 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002639 MoreAsserts.assertContentsInAnyOrder(
2640 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002641 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2642 assertFalse(dpm.isAffiliatedUser());
2643
2644 // Have the profile owner specify a set of affiliation ids that intersect with those
2645 // specified by the device owner. Check that the test user becomes affiliated.
2646 userAffiliationIds.add("yellow");
2647 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002648 MoreAsserts.assertContentsInAnyOrder(
2649 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002650 assertTrue(dpm.isAffiliatedUser());
2651
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002652 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002653 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002654 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002655 assertFalse(dpm.isAffiliatedUser());
2656
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002657 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2658 dpm.setAffiliationIds(admin2, userAffiliationIds);
2659 assertTrue(dpm.isAffiliatedUser());
2660 dpm.clearProfileOwner(admin2);
2661 assertFalse(dpm.isAffiliatedUser());
2662
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002663 // Check that the system user remains affiliated.
2664 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2665 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002666
2667 // Clear the device owner - the user becomes unaffiliated.
2668 clearDeviceOwner();
2669 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002670 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002671
2672 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002673 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002674 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2675 }
2676
2677 public void testSetUserProvisioningState_permission() throws Exception {
2678 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002679
2680 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2681 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2682 }
2683
2684 public void testSetUserProvisioningState_unprivileged() throws Exception {
2685 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002686 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2687 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2688 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002689 }
2690
2691 public void testSetUserProvisioningState_noManagement() {
2692 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002693 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002694 assertExpectException(IllegalStateException.class,
2695 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2696 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2697 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002698 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2699 }
2700
2701 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2702 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2703 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002704
2705 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2706 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2707 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2708 }
2709
2710 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2711 throws Exception {
2712 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2713 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002714
2715 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2716 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2717 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2718 }
2719
2720 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2721 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2722 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002723
2724 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2725 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2726 }
2727
2728 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2729 throws Exception {
2730 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002731
2732 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2733 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2734 DevicePolicyManager.STATE_USER_UNMANAGED);
2735 }
2736
2737 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2738 throws Exception {
2739 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002740
2741 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2742 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2743 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2744 }
2745
2746 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2747 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002748
2749 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2750 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2751 }
2752
2753 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2754 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002755
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002756 assertExpectException(IllegalStateException.class,
2757 /* messageRegex= */ "Cannot move to user provisioning state",
2758 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2759 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2760 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002761 }
2762
2763 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2764 throws Exception {
2765 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002766
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002767 assertExpectException(IllegalStateException.class,
2768 /* messageRegex= */ "Cannot move to user provisioning state",
2769 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2770 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2771 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002772 }
2773
2774 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002775 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2776 mContext.callerPermissions.add(permission.MANAGE_USERS);
2777
Alan Treadwayafad8782016-01-19 15:15:08 +00002778 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2779 for (int state : states) {
2780 dpm.setUserProvisioningState(state, userId);
2781 assertEquals(state, dpm.getUserProvisioningState());
2782 }
2783 }
2784
2785 private void setupProfileOwner() throws Exception {
2786 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2787
2788 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2789 dpm.setActiveAdmin(admin1, false);
2790 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2791
2792 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2793 }
2794
Alex Johnston8c503382019-11-19 11:12:15 +00002795 private void setupProfileOwnerOnUser0() throws Exception {
2796 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2797
2798 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2799 dpm.setActiveAdmin(admin1, false);
2800 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
2801
2802 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2803 }
2804
Alan Treadwayafad8782016-01-19 15:15:08 +00002805 private void setupDeviceOwner() throws Exception {
2806 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2807
2808 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2809 dpm.setActiveAdmin(admin1, false);
2810 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2811
2812 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2813 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002814
2815 public void testSetMaximumTimeToLock() {
2816 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2817
2818 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2819 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2820
Pavel Grafov75c0a892017-05-18 17:28:27 +01002821 reset(getServices().powerManagerInternal);
2822 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002823
2824 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002825 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2826 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002827 reset(getServices().powerManagerInternal);
2828 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002829
2830 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002831 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2832 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002833 reset(getServices().powerManagerInternal);
2834 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002835
2836 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002837 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2838 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002839 reset(getServices().powerManagerInternal);
2840 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002841
2842 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002843 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2844 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002845 reset(getServices().powerManagerInternal);
2846 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002847
2848 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002849 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2850 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002851 reset(getServices().powerManagerInternal);
2852 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002853
2854 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002855 reset(getServices().powerManagerInternal);
2856 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002857
Pavel Grafov28939982017-10-03 15:11:52 +01002858 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2859 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2860 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002861 reset(getServices().powerManagerInternal);
2862 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002863
2864 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002865 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2866 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002867 reset(getServices().powerManagerInternal);
2868 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002869
Pavel Grafov28939982017-10-03 15:11:52 +01002870 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002871 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002872 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2873 verifyStayOnWhilePluggedCleared(false);
2874 }
2875
Varun Shahb472b8f2019-09-23 23:01:06 -07002876 public void testIsActiveSupervisionApp() throws Exception {
2877 when(mServiceContext.resources
2878 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2879 .thenReturn(admin1.flattenToString());
2880
2881 final int PROFILE_USER = 15;
2882 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2883 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2884 mContext.binder.callingUid = PROFILE_ADMIN;
2885
2886 final DevicePolicyManagerInternal dpmi =
2887 LocalServices.getService(DevicePolicyManagerInternal.class);
2888 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2889 }
2890
Pavel Grafov28939982017-10-03 15:11:52 +01002891 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2892 // uses separate challenge.
2893 public void testSetMaximumTimeToLockProfile() throws Exception {
2894 final int PROFILE_USER = 15;
2895 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2896 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2897 mContext.binder.callingUid = PROFILE_ADMIN;
2898 final DevicePolicyManagerInternal dpmi =
2899 LocalServices.getService(DevicePolicyManagerInternal.class);
2900
2901 dpm.setMaximumTimeToLock(admin1, 0);
2902
2903 reset(getServices().powerManagerInternal);
2904 reset(getServices().settings);
2905
2906 // First add timeout for the profile.
2907 dpm.setMaximumTimeToLock(admin1, 10);
2908 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2909
2910 reset(getServices().powerManagerInternal);
2911 reset(getServices().settings);
2912
2913 // Add separate challenge
2914 when(getServices().lockPatternUtils
2915 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2916 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2917
2918 verifyScreenTimeoutCall(10L, PROFILE_USER);
2919 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2920
2921 reset(getServices().powerManagerInternal);
2922 reset(getServices().settings);
2923
2924 // Remove the timeout.
2925 dpm.setMaximumTimeToLock(admin1, 0);
2926 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2927 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2928
2929 reset(getServices().powerManagerInternal);
2930 reset(getServices().settings);
2931
2932 // Add it back.
2933 dpm.setMaximumTimeToLock(admin1, 10);
2934 verifyScreenTimeoutCall(10L, PROFILE_USER);
2935 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2936
2937 reset(getServices().powerManagerInternal);
2938 reset(getServices().settings);
2939
2940 // Remove separate challenge.
2941 reset(getServices().lockPatternUtils);
2942 when(getServices().lockPatternUtils
2943 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2944 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002945 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002946
2947 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2948 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2949
2950 reset(getServices().powerManagerInternal);
2951 reset(getServices().settings);
2952
2953 // Remove the timeout.
2954 dpm.setMaximumTimeToLock(admin1, 0);
2955 verifyScreenTimeoutCall(null, PROFILE_USER);
2956 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002957 }
2958
Michal Karpinski943aabd2016-10-06 11:09:25 +01002959 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2960 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2961 setupDeviceOwner();
2962 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2963
Michal Karpinskid084ca52017-01-18 15:54:18 +00002964 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2965 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2966 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2967 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2968 - ONE_MINUTE;
2969
2970 // verify that the minimum timeout cannot be modified on user builds (system property is
2971 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002972 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002973
2974 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2975 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2976 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2977
Pavel Grafov75c0a892017-05-18 17:28:27 +01002978 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002979
2980 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002981 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002982
Michal Karpinskid084ca52017-01-18 15:54:18 +00002983 // reset to default (0 means the admin is not participating, so default should be returned)
2984 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002985
2986 // aggregation should be the default if unset by any admin
2987 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2988 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2989
2990 // admin not participating by default
2991 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2992
2993 //clamping from the top
2994 dpm.setRequiredStrongAuthTimeout(admin1,
2995 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2996 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2997 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2998 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2999 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3000
Michal Karpinskid084ca52017-01-18 15:54:18 +00003001 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01003002 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3003 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3004 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3005 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3006
3007 // clamping from the bottom
3008 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
3009 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3010 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3011
Michal Karpinskid084ca52017-01-18 15:54:18 +00003012 // values within range
3013 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
3014 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
3015 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
3016
3017 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3018 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
3019 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01003020
3021 // reset to default
3022 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3023 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3024 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3025 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3026
3027 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003028 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3029 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01003030 }
3031
Pavel Grafov28939982017-10-03 15:11:52 +01003032 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003033 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003034 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01003035 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003036 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003037 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01003038 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003039 }
Pavel Grafov28939982017-10-03 15:11:52 +01003040 }
3041
3042 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003043 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
3044 // UnfinishedVerificationException.
3045 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003046
Esteban Talavera01576862016-12-15 11:16:44 +00003047 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003048 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00003049 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003050 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003051 .thenReturn(false);
3052 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003053 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3054 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003055 .thenReturn(true);
3056 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3057
3058 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 }
Victor Chang3e794af2016-03-04 13:48:17 +00003060
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003061 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
3062 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003063 mContext.packageName = admin1.getPackageName();
3064 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003066 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003067 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3068 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3069 false);
3070 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3071 }
3072
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003073 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
3074 setup_DeviceAdminFeatureOff();
3075 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3076 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3077 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Yanli Wan01c92552019-11-18 16:07:54 -08003078 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3079 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003080 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3081 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3082 assertCheckProvisioningPreCondition(
3083 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3084 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3085 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3086 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3087 }
3088
Esteban Talavera01576862016-12-15 11:16:44 +00003089 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003090 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003091 .thenReturn(false);
3092 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003093 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3094 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003095 .thenReturn(true);
3096 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3097
3098 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003099 }
Victor Chang3e794af2016-03-04 13:48:17 +00003100
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003101 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
3102 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003103 mContext.packageName = admin1.getPackageName();
3104 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003106 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003107 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3108 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3109 false);
3110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3111
3112 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003113 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00003114 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003115 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3117 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3118 true);
3119 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3120 }
3121
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003122 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
3123 setup_ManagedProfileFeatureOff();
3124 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3125 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3126 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003127 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3128 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003129 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3130 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3131 assertCheckProvisioningPreCondition(
3132 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3133 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3134 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3135 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3136
3137 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003138 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003139 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3140 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003141 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3142 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003143 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3144 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3145 assertCheckProvisioningPreCondition(
3146 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3147 DevicePolicyManager.CODE_OK);
3148 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3149 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3150 }
3151
Esteban Talavera01576862016-12-15 11:16:44 +00003152 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003153 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003154 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003155 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3156 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003157 .thenReturn(true);
3158 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3159
3160 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003161 }
Victor Chang3e794af2016-03-04 13:48:17 +00003162
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003163 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
3164 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003165 mContext.packageName = admin1.getPackageName();
3166 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003167 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003168 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003169 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3170 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3171 false /* because of non-split user */);
3172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3173 false /* because of non-split user */);
3174 }
3175
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003176 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003177 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003178 setup_nonSplitUser_firstBoot_primaryUser();
3179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3180 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3181 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003182 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3183 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003184 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3185 DevicePolicyManager.CODE_OK);
3186 assertCheckProvisioningPreCondition(
3187 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3188 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3189 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3190 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3191 }
3192
Esteban Talavera01576862016-12-15 11:16:44 +00003193 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003194 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003195 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003196 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3197 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003198 .thenReturn(true);
3199 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3200
3201 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003202 }
Victor Chang3e794af2016-03-04 13:48:17 +00003203
Nicolas Prevot45d29072017-01-18 16:11:19 +00003204 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
3205 setDeviceOwner();
3206 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3207 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3208 }
3209
3210 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3211 setup_nonSplitUser_withDo_primaryUser();
3212 final int MANAGED_PROFILE_USER_ID = 18;
3213 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003214 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003215 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003216 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003217 true)).thenReturn(true);
3218 }
3219
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003220 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3221 throws Exception {
3222 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003223 mContext.packageName = admin1.getPackageName();
3224 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003225 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3226 false/* because of completed device setup */);
Yanli Wan01c92552019-11-18 16:07:54 -08003227 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3228 false/* because of completed device setup */);
Victor Chang3e794af2016-03-04 13:48:17 +00003229 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3230 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3231 false/* because of non-split user */);
3232 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3233 false/* because of non-split user */);
3234 }
3235
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003236 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3237 throws Exception {
3238 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3239 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3240 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3241 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Yanli Wan01c92552019-11-18 16:07:54 -08003242 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3243 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003244 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3245 DevicePolicyManager.CODE_OK);
3246 assertCheckProvisioningPreCondition(
3247 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3248 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3249 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3250 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3251 }
3252
Nicolas Prevot45d29072017-01-18 16:11:19 +00003253 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3254 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003255 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003256 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3257
3258 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3259 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Yanli Wan01c92552019-11-18 16:07:54 -08003260 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3261 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003262 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003263 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003264
Eran Messeri6ad0e192019-12-01 20:01:21 +00003265 // COMP mode NOT is allowed.
Esteban Talavera01576862016-12-15 11:16:44 +00003266 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003267 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3268 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003269
Eran Messeri6ad0e192019-12-01 20:01:21 +00003270 // And other DPCs can NOT provision a managed profile.
Esteban Talavera01576862016-12-15 11:16:44 +00003271 assertCheckProvisioningPreCondition(
3272 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003273 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003274 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003275 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3276 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3277 }
Esteban Talavera01576862016-12-15 11:16:44 +00003278
Nicolas Prevot45d29072017-01-18 16:11:19 +00003279 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3280 throws Exception {
3281 setup_nonSplitUser_withDo_primaryUser();
3282 mContext.packageName = admin1.getPackageName();
3283 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003284 // The DO should not be allowed to initiate provisioning if the restriction is set by
3285 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003286 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003287 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3288 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3289 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003290 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003291 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3292 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3293 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3294 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003295 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003296 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3297
3298 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003299 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003300 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003301 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003302 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3303 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3304 }
3305
Eran Messeri6ad0e192019-12-01 20:01:21 +00003306 public void testCheckCannotSetProfileOwnerWithDeviceOwner() throws Exception {
3307 setup_nonSplitUser_withDo_primaryUser();
3308 final int managedProfileUserId = 18;
3309 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 1308);
3310
3311 final int userId = UserHandle.getUserId(managedProfileAdminUid);
3312 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
3313 UserHandle.USER_SYSTEM);
3314 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3315 setUpPackageManagerForFakeAdmin(admin1, managedProfileAdminUid, admin1);
3316 dpm.setActiveAdmin(admin1, false, userId);
3317 assertFalse(dpm.setProfileOwner(admin1, null, userId));
3318 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3319 }
3320
3321 public void testCheckProvisioningPreCondition_nonSplitUser_attemptingComp() throws Exception {
Nicolas Prevot45d29072017-01-18 16:11:19 +00003322 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3323 mContext.packageName = admin1.getPackageName();
3324 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3325
3326 // We can delete the managed profile to create a new one, so provisioning is allowed.
3327 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003328 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3329 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003330 assertCheckProvisioningPreCondition(
3331 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3332 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003333 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3334 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003335 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3336 }
3337
3338 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3339 throws Exception {
3340 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3341 mContext.packageName = admin1.getPackageName();
3342 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003343 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003344 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3345 eq(UserHandle.SYSTEM)))
3346 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003347 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003348 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3349 eq(UserHandle.SYSTEM)))
3350 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003351
3352 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003353 assertCheckProvisioningPreCondition(
3354 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3355 DpmMockContext.ANOTHER_PACKAGE_NAME,
3356 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3357 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3358 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003359
3360 // But the device owner can still do it because it has set the restriction itself.
3361 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003362 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3363 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003364 }
3365
3366 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003367 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003368 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003369 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3370 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003371 .thenReturn(false);
3372 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3373
3374 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003375 }
Victor Chang3e794af2016-03-04 13:48:17 +00003376
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003377 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3378 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003379 mContext.packageName = admin1.getPackageName();
3380 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003381 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003382 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003383 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3384 false /* because canAddMoreManagedProfiles returns false */);
3385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3386 true);
3387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3388 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003389 }
3390
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003391 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3392 throws Exception {
3393 setup_splitUser_firstBoot_systemUser();
3394 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3395 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3396 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003397 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3398 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003399 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003400 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003401 assertCheckProvisioningPreCondition(
3402 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3403 DevicePolicyManager.CODE_OK);
3404 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3405 DevicePolicyManager.CODE_SYSTEM_USER);
3406 }
3407
Esteban Talavera01576862016-12-15 11:16:44 +00003408 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003409 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003410 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003411 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3412 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003413 .thenReturn(false);
3414 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3415
3416 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003417 }
Victor Chang3e794af2016-03-04 13:48:17 +00003418
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003419 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3420 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003421 mContext.packageName = admin1.getPackageName();
3422 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003423 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3424 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003425 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3426 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003427 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3428 false /* because canAddMoreManagedProfiles returns false */);
3429 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3430 true/* it's undefined behavior. Can be changed into false in the future */);
3431 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3432 false/* because calling uid is system user */);
3433 }
3434
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003435 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3436 throws Exception {
3437 setup_splitUser_afterDeviceSetup_systemUser();
3438 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3439 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3440 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003441 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3442 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003443 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003444 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003445 assertCheckProvisioningPreCondition(
3446 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3447 DevicePolicyManager.CODE_OK);
3448 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3449 DevicePolicyManager.CODE_SYSTEM_USER);
3450 }
3451
Esteban Talavera01576862016-12-15 11:16:44 +00003452 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003453 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003454 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003455 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3456 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003457 true)).thenReturn(true);
3458 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3459
3460 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003461 }
Victor Chang3e794af2016-03-04 13:48:17 +00003462
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003463 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3464 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003465 mContext.packageName = admin1.getPackageName();
3466 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003467 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003468 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003469 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3470 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3471 true);
3472 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003473 }
3474
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003475 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003476 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003477 setup_splitUser_firstBoot_primaryUser();
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,
3484 DevicePolicyManager.CODE_OK);
3485 assertCheckProvisioningPreCondition(
3486 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3487 DevicePolicyManager.CODE_OK);
3488 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3489 DevicePolicyManager.CODE_OK);
3490 }
3491
Esteban Talavera01576862016-12-15 11:16:44 +00003492 private void setup_splitUser_afterDeviceSetup_primaryUser() 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(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003497 true)).thenReturn(true);
3498 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3499
3500 mContext.binder.callingUid = DpmMockContext.CALLER_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_primaryUser()
3504 throws Exception {
3505 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003506 mContext.packageName = admin1.getPackageName();
3507 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003508 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3509 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003510 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3511 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003512 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
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 user setup completed */);
3517 }
3518
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003519 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003520 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003521 setup_splitUser_afterDeviceSetup_primaryUser();
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,
3528 DevicePolicyManager.CODE_OK);
3529 assertCheckProvisioningPreCondition(
3530 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3531 DevicePolicyManager.CODE_OK);
3532 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3533 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3534 }
3535
Esteban Talavera01576862016-12-15 11:16:44 +00003536 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003537 setDeviceOwner();
3538
Pavel Grafov75c0a892017-05-18 17:28:27 +01003539 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003540 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003541 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3542 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003543 .thenReturn(false);
3544 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3545
3546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003547 }
Victor Chang3e794af2016-03-04 13:48:17 +00003548
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003549 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3550 throws Exception {
3551 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003552 mContext.packageName = admin1.getPackageName();
3553 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003554 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3555 false /* can't provision managed profile on system user */);
3556 }
3557
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003558 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003559 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003560 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3561 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3562 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3563 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3564 }
3565
3566 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003567 setDeviceOwner();
3568
Pavel Grafov75c0a892017-05-18 17:28:27 +01003569 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003570 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003571 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Eran Messeri6ad0e192019-12-01 20:01:21 +00003572 when(getServices().userManager.getProfileParent(DpmMockContext.CALLER_USER_HANDLE))
3573 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003574 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003575 true)).thenReturn(true);
3576 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3577
3578 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003579 }
Victor Chang3e794af2016-03-04 13:48:17 +00003580
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003581 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3582 throws Exception {
3583 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003584 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3585 mContext.packageName = admin1.getPackageName();
Eran Messeri6ad0e192019-12-01 20:01:21 +00003586 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003587 }
3588
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003589 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003590 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003591 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3592 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003593
Eran Messeri6ad0e192019-12-01 20:01:21 +00003594 // COMP mode is NOT allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003595 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003596 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003597 }
3598
3599 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003600 setDeviceOwner();
3601
Pavel Grafov75c0a892017-05-18 17:28:27 +01003602 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003603 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003604 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3605 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003606 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3607 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003608 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003609 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003610 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003611 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003612 true)).thenReturn(true);
3613 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3614
3615 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003616 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003617
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003618 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3619 throws Exception {
3620 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003621 mContext.packageName = admin1.getPackageName();
3622 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003623 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3624 }
3625
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003626 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3627 throws Exception {
3628 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3629 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3630 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3631 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3632 }
3633
3634 public void testCheckProvisioningPreCondition_permission() {
3635 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003636 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3637 () -> dpm.checkProvisioningPreCondition(
3638 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003639 }
3640
Victor Chang3577ed22016-08-25 18:49:26 +01003641 public void testForceUpdateUserSetupComplete_permission() {
3642 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003643 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3644 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003645 }
3646
3647 public void testForceUpdateUserSetupComplete_systemUser() {
3648 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3649 // GIVEN calling from user 20
3650 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003651 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3652 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003653 }
3654
3655 public void testForceUpdateUserSetupComplete_userbuild() {
3656 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3657 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3658
3659 final int userId = UserHandle.USER_SYSTEM;
3660 // GIVEN userComplete is false in SettingsProvider
3661 setUserSetupCompleteForUser(false, userId);
3662
3663 // GIVEN userComplete is true in DPM
3664 DevicePolicyManagerService.DevicePolicyData userData =
3665 new DevicePolicyManagerService.DevicePolicyData(userId);
3666 userData.mUserSetupComplete = true;
3667 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3668
3669 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003670 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003671
3672 assertTrue(dpms.hasUserSetupCompleted());
3673
3674 dpm.forceUpdateUserSetupComplete();
3675
3676 // THEN the state in dpms is not changed
3677 assertTrue(dpms.hasUserSetupCompleted());
3678 }
3679
3680 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3681 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3682 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3683
3684 final int userId = UserHandle.USER_SYSTEM;
3685 // GIVEN userComplete is false in SettingsProvider
3686 setUserSetupCompleteForUser(false, userId);
3687
3688 // GIVEN userComplete is true in DPM
3689 DevicePolicyManagerService.DevicePolicyData userData =
3690 new DevicePolicyManagerService.DevicePolicyData(userId);
3691 userData.mUserSetupComplete = true;
3692 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3693
3694 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003695 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003696
3697 assertTrue(dpms.hasUserSetupCompleted());
3698
3699 dpm.forceUpdateUserSetupComplete();
3700
3701 // THEN the state in dpms is not changed
3702 assertFalse(dpms.hasUserSetupCompleted());
3703 }
3704
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003705 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003706 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003707 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003708
3709 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3710 runAsCaller(mAdmin1Context, dpms, dpm -> {
3711 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3712 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003713 }
3714
3715 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3716 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3717 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003718
3719 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3720 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003721 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003722 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3723 .thenReturn(true);
3724
3725 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003726 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003727
3728 // Enabling logging should not change the timestamp.
3729 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003730 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003731 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003732 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003733 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003734 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003735
3736 // Retrieving the logs should update the timestamp.
3737 final long beforeRetrieval = System.currentTimeMillis();
3738 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003739 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003740 final long afterRetrieval = System.currentTimeMillis();
3741 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3742 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3743
3744 // Retrieving the pre-boot logs should update the timestamp.
3745 Thread.sleep(2);
3746 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003747 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003748 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3749
3750 // Checking the timestamp again should not change it.
3751 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003752 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003753
3754 // Retrieving the logs again should update the timestamp.
3755 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003756 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003757 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3758
3759 // Disabling logging should not change the timestamp.
3760 Thread.sleep(2);
3761 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003762 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003763
3764 // Restarting the DPMS should not lose the timestamp.
3765 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003766 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003767
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003768 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3769 mContext.binder.callingUid = 1234567;
3770 mContext.callerPermissions.add(permission.MANAGE_USERS);
3771 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3772 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3773
3774 // System can retrieve the timestamp.
3775 mContext.binder.clearCallingIdentity();
3776 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3777
3778 // Removing the device owner should clear the timestamp.
3779 clearDeviceOwner();
3780 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003781 }
3782
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003783 public void testSetLockdownAdminConfiguredNetworksWithDO() throws Exception {
3784 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3785 setupDeviceOwner();
3786 dpm.setLockdownAdminConfiguredNetworks(admin1, true);
3787 verify(getServices().settings).settingsGlobalPutInt(
3788 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3789
3790 dpm.setLockdownAdminConfiguredNetworks(admin1, false);
3791 verify(getServices().settings).settingsGlobalPutInt(
3792 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3793 }
3794
3795 public void testSetLockdownAdminConfiguredNetworksWithPO() throws Exception {
3796 setupProfileOwner();
3797 assertExpectException(SecurityException.class, null,
3798 () -> dpm.setLockdownAdminConfiguredNetworks(admin1, false));
3799 verify(getServices().settings, never()).settingsGlobalPutInt(
3800 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3801 }
3802
3803 public void testSetLockdownAdminConfiguredNetworksWithPOOfOrganizationOwnedDevice()
3804 throws Exception {
3805 setupProfileOwner();
3806 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3807 dpm.setLockdownAdminConfiguredNetworks(admin1, true);
3808 verify(getServices().settings).settingsGlobalPutInt(
3809 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3810
3811 dpm.setLockdownAdminConfiguredNetworks(admin1, false);
3812 verify(getServices().settings).settingsGlobalPutInt(
3813 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3814 }
3815
yuemingw0de748d2017-11-15 19:22:27 +00003816 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3817 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3818 setupDeviceOwner();
3819 assertExpectException(SecurityException.class, null, () ->
3820 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3821 }
3822
yuemingwc0281f12018-03-28 15:58:49 +01003823 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003824 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3825 setupDeviceOwner();
3826 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003827 verify(getServices().settings).settingsSystemPutStringForUser(
3828 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3829 }
3830
3831 public void testSetSystemSettingWithPO() throws Exception {
3832 setupProfileOwner();
3833 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3834 verify(getServices().settings).settingsSystemPutStringForUser(
3835 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003836 }
3837
Alex Johnston8c503382019-11-19 11:12:15 +00003838 public void testSetAutoTimeModifiesSetting() throws Exception {
3839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3840 setupDeviceOwner();
3841 dpm.setAutoTime(admin1, true);
3842 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3843
3844 dpm.setAutoTime(admin1, false);
3845 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3846 }
3847
3848 public void testSetAutoTimeWithPOOnUser0() throws Exception {
3849 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3850 setupProfileOwnerOnUser0();
3851 dpm.setAutoTime(admin1, true);
3852 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3853
3854 dpm.setAutoTime(admin1, false);
3855 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3856 }
3857
3858 public void testSetAutoTimeFailWithPONotOnUser0() throws Exception {
3859 setupProfileOwner();
3860 assertExpectException(SecurityException.class, null, () -> dpm.setAutoTime(admin1, false));
3861 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3862 }
3863
3864 public void testSetAutoTimeWithPOOfOrganizationOwnedDevice() throws Exception {
3865 setupProfileOwner();
3866 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3867
3868 dpm.setAutoTime(admin1, true);
3869 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3870
3871 dpm.setAutoTime(admin1, false);
3872 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3873 }
3874
Alex Johnstona44d7292019-12-12 15:34:35 +00003875 public void testSetAutoTimeZoneModifiesSetting() throws Exception {
3876 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3877 setupDeviceOwner();
3878 dpm.setAutoTimeZone(admin1, true);
3879 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3880
3881 dpm.setAutoTimeZone(admin1, false);
3882 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3883 }
3884
3885 public void testSetAutoTimeZoneWithPOOnUser0() throws Exception {
3886 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3887 setupProfileOwnerOnUser0();
3888 dpm.setAutoTimeZone(admin1, true);
3889 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3890
3891 dpm.setAutoTimeZone(admin1, false);
3892 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3893 }
3894
3895 public void testSetAutoTimeZoneFailWithPONotOnUser0() throws Exception {
3896 setupProfileOwner();
3897 assertExpectException(SecurityException.class, null,
3898 () -> dpm.setAutoTimeZone(admin1, false));
3899 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
3900 0);
3901 }
3902
3903 public void testSetAutoTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
3904 setupProfileOwner();
3905 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3906
3907 dpm.setAutoTimeZone(admin1, true);
3908 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3909
3910 dpm.setAutoTimeZone(admin1, false);
3911 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3912 }
3913
Eran Messeria1015c82019-12-18 15:27:04 +00003914 public void testIsOrganizationOwnedDevice() throws Exception {
3915 setupProfileOwner();
3916 // Set up the user manager to return correct user info
3917 UserInfo managedProfileUserInfo = new UserInfo(DpmMockContext.CALLER_USER_HANDLE,
3918 "managed profile",
3919 UserInfo.FLAG_MANAGED_PROFILE);
3920 when(getServices().userManager.getUsers())
3921 .thenReturn(Arrays.asList(managedProfileUserInfo));
3922
Eran Messeri41c2aed2020-01-13 15:10:12 +00003923 // Any caller should be able to call this method.
Eran Messeria1015c82019-12-18 15:27:04 +00003924 assertFalse(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3925 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3926 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3927
3928 // A random caller from another user should also be able to get the right result.
3929 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
3930 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3931 }
3932
yuemingwe43cdf72017-10-12 16:52:11 +01003933 public void testSetTime() throws Exception {
3934 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3935 setupDeviceOwner();
3936 dpm.setTime(admin1, 0);
Neil Fullere3767562019-11-23 11:33:57 +00003937
3938 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3939 @Override
3940 public boolean matches(Object item) {
3941 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3942 return suggestion.getUtcTime().getValue() == 0;
3943 }
3944 @Override
3945 public void describeTo(Description description) {
3946 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3947 }
3948 };
3949 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
yuemingwe43cdf72017-10-12 16:52:11 +01003950 }
3951
3952 public void testSetTimeFailWithPO() throws Exception {
3953 setupProfileOwner();
3954 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3955 }
3956
Alex Johnstone81f05c2019-12-19 12:06:24 +00003957 public void testSetTimeWithPOOfOrganizationOwnedDevice() throws Exception {
3958 setupProfileOwner();
3959 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3960 dpm.setTime(admin1, 0);
3961
3962 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3963 @Override
3964 public boolean matches(Object item) {
3965 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3966 return suggestion.getUtcTime().getValue() == 0;
3967 }
3968 @Override
3969 public void describeTo(Description description) {
3970 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3971 }
3972 };
3973 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
3974 }
3975
yuemingwe43cdf72017-10-12 16:52:11 +01003976 public void testSetTimeWithAutoTimeOn() throws Exception {
3977 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3978 setupDeviceOwner();
3979 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3980 .thenReturn(1);
3981 assertFalse(dpm.setTime(admin1, 0));
3982 }
3983
3984 public void testSetTimeZone() throws Exception {
3985 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3986 setupDeviceOwner();
3987 dpm.setTimeZone(admin1, "Asia/Shanghai");
Neil Fuller106f18a2019-12-04 13:27:04 +00003988 ManualTimeZoneSuggestion suggestion =
3989 TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
3990 verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
yuemingwe43cdf72017-10-12 16:52:11 +01003991 }
3992
3993 public void testSetTimeZoneFailWithPO() throws Exception {
3994 setupProfileOwner();
3995 assertExpectException(SecurityException.class, null,
3996 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3997 }
3998
Alex Johnstone81f05c2019-12-19 12:06:24 +00003999 public void testSetTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
4000 setupProfileOwner();
4001 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
4002 dpm.setTimeZone(admin1, "Asia/Shanghai");
4003 ManualTimeZoneSuggestion suggestion =
4004 TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
4005 verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
4006 }
4007
yuemingwe43cdf72017-10-12 16:52:11 +01004008 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
4009 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4010 setupDeviceOwner();
4011 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
4012 .thenReturn(1);
4013 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
4014 }
4015
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004016 public void testGetLastBugReportRequestTime() throws Exception {
4017 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4018 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004019
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004020 mContext.packageName = admin1.getPackageName();
4021 mContext.applicationInfo = new ApplicationInfo();
4022 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4023 .thenReturn(Color.WHITE);
4024 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4025 anyObject())).thenReturn(Color.WHITE);
4026
Esteban Talaverad36dd152016-12-15 08:51:45 +00004027 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4028 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004029 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00004030
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004031 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004032 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004033
4034 // Requesting a bug report should update the timestamp.
4035 final long beforeRequest = System.currentTimeMillis();
4036 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004037 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004038 final long afterRequest = System.currentTimeMillis();
4039 assertTrue(bugReportRequestTime >= beforeRequest);
4040 assertTrue(bugReportRequestTime <= afterRequest);
4041
4042 // Checking the timestamp again should not change it.
4043 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004044 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004045
4046 // Restarting the DPMS should not lose the timestamp.
4047 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004048 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004049
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004050 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4051 mContext.binder.callingUid = 1234567;
4052 mContext.callerPermissions.add(permission.MANAGE_USERS);
4053 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4054 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4055
4056 // System can retrieve the timestamp.
4057 mContext.binder.clearCallingIdentity();
4058 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4059
4060 // Removing the device owner should clear the timestamp.
4061 clearDeviceOwner();
4062 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004063 }
4064
4065 public void testGetLastNetworkLogRetrievalTime() throws Exception {
4066 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4067 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004068 mContext.packageName = admin1.getPackageName();
4069 mContext.applicationInfo = new ApplicationInfo();
4070 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4071 .thenReturn(Color.WHITE);
4072 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4073 anyObject())).thenReturn(Color.WHITE);
4074
4075 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4076 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004077 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01004078 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004079 .thenReturn(true);
4080
4081 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004082 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004083
4084 // Attempting to retrieve logs without enabling logging should not change the timestamp.
4085 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004086 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004087
4088 // Enabling logging should not change the timestamp.
4089 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004090 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004091
4092 // Retrieving the logs should update the timestamp.
4093 final long beforeRetrieval = System.currentTimeMillis();
4094 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004095 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004096 final long afterRetrieval = System.currentTimeMillis();
4097 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
4098 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
4099
4100 // Checking the timestamp again should not change it.
4101 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004102 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004103
4104 // Retrieving the logs again should update the timestamp.
4105 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004106 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004107 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
4108
4109 // Disabling logging should not change the timestamp.
4110 Thread.sleep(2);
4111 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004112 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004113
4114 // Restarting the DPMS should not lose the timestamp.
4115 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004116 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4117
4118 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4119 mContext.binder.callingUid = 1234567;
4120 mContext.callerPermissions.add(permission.MANAGE_USERS);
4121 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4122 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4123
4124 // System can retrieve the timestamp.
4125 mContext.binder.clearCallingIdentity();
4126 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4127
4128 // Removing the device owner should clear the timestamp.
4129 clearDeviceOwner();
4130 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004131 }
4132
Tony Mak2f26b792016-11-28 17:54:51 +00004133 public void testGetBindDeviceAdminTargetUsers() throws Exception {
4134 // Setup device owner.
4135 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4136 setupDeviceOwner();
4137
4138 // Only device owner is setup, the result list should be empty.
4139 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4140 MoreAsserts.assertEmpty(targetUsers);
4141
Tony Mak2f26b792016-11-28 17:54:51 +00004142 // Add a secondary user, it should never talk with.
4143 final int ANOTHER_USER_ID = 36;
Alex Johnston755e3772019-11-29 03:27:22 +00004144 getServices().addUser(ANOTHER_USER_ID, 0, UserManager.USER_TYPE_FULL_SECONDARY);
Tony Mak2f26b792016-11-28 17:54:51 +00004145
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004146 // Since the managed profile is not affiliated, they should not be allowed to talk to each
4147 // other.
4148 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4149 MoreAsserts.assertEmpty(targetUsers);
4150
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004151 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01004152 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004153 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4154 dpm.setAffiliationIds(admin1, userAffiliationIds);
4155
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004156 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01004157 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004158
4159 // Since the managed profile is not affiliated any more, they should not be allowed to talk
4160 // to each other.
4161 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4162 MoreAsserts.assertEmpty(targetUsers);
4163
4164 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4165 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4166 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00004167 }
4168
Jason Parks3c13b642017-11-28 15:39:43 -06004169 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01004170 verifyLockTaskState(userId, new String[0],
4171 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06004172 }
4173
4174 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
4175 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004176 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06004177 }
4178
4179 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
4180 int flags) throws Exception {
4181 mContext.binder.callingUid = uid;
4182 dpm.setLockTaskPackages(who, packages);
4183 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
4184 for (String p : packages) {
4185 assertTrue(dpm.isLockTaskPermitted(p));
4186 }
4187 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
4188 // Test to see if set lock task features can be set
4189 dpm.setLockTaskFeatures(who, flags);
4190 verifyLockTaskState(userId, packages, flags);
4191 }
4192
4193 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
4194 int flags) throws Exception {
4195 mContext.binder.callingUid = uid;
4196 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4197 () -> dpm.setLockTaskPackages(who, packages));
4198 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4199 () -> dpm.getLockTaskPackages(who));
4200 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
4201 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4202 () -> dpm.setLockTaskFeatures(who, flags));
4203 }
4204
Jason Parks3c13b642017-11-28 15:39:43 -06004205 public void testLockTaskPolicyForProfileOwner() throws Exception {
4206 // Setup a PO
4207 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4208 setAsProfileOwner(admin1);
4209 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
4210
4211 final String[] poPackages = {"poPackage1", "poPackage2"};
4212 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004213 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4214 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004215 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
4216 poPackages, poFlags);
4217
4218 // Set up a managed profile managed by different package (package name shouldn't matter)
4219 final int MANAGED_PROFILE_USER_ID = 15;
4220 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
4221 final ComponentName adminDifferentPackage =
4222 new ComponentName("another.package", "whatever.class");
4223 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
4224 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
4225
4226 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
4227 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4228 final String[] mpoPackages = {"poPackage1", "poPackage2"};
4229 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004230 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4231 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004232 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00004233 }
4234
Benjamin Franzcaffa772018-02-05 16:36:10 +00004235 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
4236 // Setup a device owner.
4237 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4238 setupDeviceOwner();
4239 // Lock task policy is updated when loading user data.
4240 verifyLockTaskState(UserHandle.USER_SYSTEM);
4241
4242 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4243 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4244 assertExpectException(IllegalArgumentException.class,
4245 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4246 () -> dpm.setLockTaskFeatures(admin1, flags));
4247 }
4248
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004249 public void testSecondaryLockscreen_profileOwner() throws Exception {
4250 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4251
4252 // Initial state is disabled.
4253 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4254
4255 // Profile owner can set enabled state.
4256 setAsProfileOwner(admin1);
4257 dpm.setSecondaryLockscreenEnabled(admin1, true);
4258 assertTrue(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4259
4260 // Managed profile managed by different package is unaffiliated - cannot set enabled.
4261 final int managedProfileUserId = 15;
4262 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 20456);
4263 final ComponentName adminDifferentPackage =
4264 new ComponentName("another.package", "whatever.class");
4265 addManagedProfile(adminDifferentPackage, managedProfileAdminUid, admin2);
4266 mContext.binder.callingUid = managedProfileAdminUid;
4267 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4268 () -> dpm.setSecondaryLockscreenEnabled(adminDifferentPackage, false));
4269 }
4270
4271 public void testSecondaryLockscreen_deviceOwner() throws Exception {
4272 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4273
4274 // Initial state is disabled.
4275 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.USER_SYSTEM));
4276
4277 // Device owners can set enabled state.
4278 setupDeviceOwner();
4279 dpm.setSecondaryLockscreenEnabled(admin1, true);
4280 assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.USER_SYSTEM));
4281 }
4282
4283 public void testSecondaryLockscreen_nonOwner() throws Exception {
4284 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4285
4286 // Initial state is disabled.
4287 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4288
4289 // Non-DO/PO cannot set enabled state.
4290 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4291 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
4292 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4293 }
4294
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01004295 public void testIsDeviceManaged() throws Exception {
4296 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4297 setupDeviceOwner();
4298
4299 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
4300 // find out that the device has a device owner.
4301 assertTrue(dpm.isDeviceManaged());
4302 mContext.binder.callingUid = 1234567;
4303 mContext.callerPermissions.add(permission.MANAGE_USERS);
4304 assertTrue(dpm.isDeviceManaged());
4305 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4306 mContext.binder.clearCallingIdentity();
4307 assertTrue(dpm.isDeviceManaged());
4308
4309 clearDeviceOwner();
4310
4311 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4312 // not have a device owner.
4313 mContext.binder.callingUid = 1234567;
4314 mContext.callerPermissions.add(permission.MANAGE_USERS);
4315 assertFalse(dpm.isDeviceManaged());
4316 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4317 mContext.binder.clearCallingIdentity();
4318 assertFalse(dpm.isDeviceManaged());
4319 }
4320
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004321 public void testDeviceOwnerOrganizationName() throws Exception {
4322 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4323 setupDeviceOwner();
4324
4325 dpm.setOrganizationName(admin1, "organization");
4326
4327 // Device owner can retrieve organization managing the device.
4328 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4329
4330 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4331 mContext.binder.callingUid = 1234567;
4332 mContext.callerPermissions.add(permission.MANAGE_USERS);
4333 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4334 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4335
4336 // System can retrieve organization managing the device.
4337 mContext.binder.clearCallingIdentity();
4338 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4339
4340 // Removing the device owner clears the organization managing the device.
4341 clearDeviceOwner();
4342 assertNull(dpm.getDeviceOwnerOrganizationName());
4343 }
4344
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004345 public void testWipeDataManagedProfile() throws Exception {
4346 final int MANAGED_PROFILE_USER_ID = 15;
4347 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4348 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4349 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4350
4351 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004352 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004353 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004354 // Get mock reason string since we throw an IAE with empty string input.
4355 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4356 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004357
4358 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004359 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004360 MANAGED_PROFILE_USER_ID);
4361 }
4362
4363 public void testWipeDataManagedProfileDisallowed() throws Exception {
4364 final int MANAGED_PROFILE_USER_ID = 15;
4365 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4366 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4367
4368 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004369 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004370 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4371
Pavel Grafov75c0a892017-05-18 17:28:27 +01004372 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004373 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4374 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4375 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004376 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4377 thenReturn("Just a test string.");
4378
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004379 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004380 // The PO is not allowed to remove the profile if the user restriction was set on the
4381 // profile by the system
4382 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4383 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004384 }
4385
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004386 public void testWipeDataDeviceOwner() throws Exception {
4387 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004388 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004389 UserManager.DISALLOW_FACTORY_RESET,
4390 UserHandle.SYSTEM))
4391 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004392 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4393 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004394
4395 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004396 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004397 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4398 /*wipeEuicc=*/ eq(false));
4399 }
4400
4401 public void testWipeEuiccDataEnabled() throws Exception {
4402 setDeviceOwner();
4403 when(getServices().userManager.getUserRestrictionSource(
4404 UserManager.DISALLOW_FACTORY_RESET,
4405 UserHandle.SYSTEM))
4406 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004407 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4408 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004409
4410 dpm.wipeData(WIPE_EUICC);
4411 verify(getServices().recoverySystem).rebootWipeUserData(
4412 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4413 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004414 }
4415
4416 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4417 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004418 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004419 UserManager.DISALLOW_FACTORY_RESET,
4420 UserHandle.SYSTEM))
4421 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004422 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4423 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004424 // The DO is not allowed to wipe the device if the user restriction was set
4425 // by the system
4426 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4427 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004428 }
4429
4430 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4431 final int MANAGED_PROFILE_USER_ID = 15;
4432 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4433 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4434
4435 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004436 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004437 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4438
Pavel Grafov75c0a892017-05-18 17:28:27 +01004439 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004440 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4441 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4442 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4443
4444 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4445 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4446
4447 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4448 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4449 // Failed password attempts on the parent user are taken into account, as there isn't a
4450 // separate work challenge.
4451 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4452 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4453 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4454
4455 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4456 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004457 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004458 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004459 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004460 }
4461
4462 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4463 throws Exception {
4464 final int MANAGED_PROFILE_USER_ID = 15;
4465 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4466 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4467
4468 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004469 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004470 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4471
Pavel Grafov75c0a892017-05-18 17:28:27 +01004472 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004473 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4474 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4475 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4476
4477 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4478 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4479
4480 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4481 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4482 // Failed password attempts on the parent user are taken into account, as there isn't a
4483 // separate work challenge.
4484 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4485 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4486 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4487
4488 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4489 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004490 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004491 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004492 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004493 }
4494
4495 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4496 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004497 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004498 UserManager.DISALLOW_FACTORY_RESET,
4499 UserHandle.SYSTEM))
4500 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4501
4502 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4503
4504 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4505 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4506 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4507 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4508 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4509
4510 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4511 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004512 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004513 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4514 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004515 }
4516
4517 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4518 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004519 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004520 UserManager.DISALLOW_FACTORY_RESET,
4521 UserHandle.SYSTEM))
4522 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4523
4524 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4525
4526 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4527 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4528 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4529 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4530 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4531
4532 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004533 verifyZeroInteractions(getServices().recoverySystem);
4534 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004535 .removeUserEvenWhenDisallowed(anyInt());
4536 }
4537
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004538 public void testGetPermissionGrantState() throws Exception {
4539 final String permission = "some.permission";
4540 final String app1 = "com.example.app1";
4541 final String app2 = "com.example.app2";
4542
Pavel Grafov75c0a892017-05-18 17:28:27 +01004543 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004544 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004545 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004546 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004547 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004548 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4549 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004550 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004551 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004552 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004553 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004554 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004555 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4556
4557 // System can retrieve permission grant state.
4558 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004559 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004560 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4561 dpm.getPermissionGrantState(null, app1, permission));
4562 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4563 dpm.getPermissionGrantState(null, app2, permission));
4564
4565 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004566 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4567 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004568 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4569 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004570
4571 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004572 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4573 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004574 setAsProfileOwner(admin1);
4575 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4576 dpm.getPermissionGrantState(admin1, app1, permission));
4577 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4578 dpm.getPermissionGrantState(admin1, app2, permission));
4579 }
4580
Rubin Xuaab7a412016-12-30 21:13:29 +00004581 public void testResetPasswordWithToken() throws Exception {
4582 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4583 setupDeviceOwner();
4584 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004585 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4586 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4587
Rubin Xuaab7a412016-12-30 21:13:29 +00004588 // test adding a token
4589 final byte[] token = new byte[32];
4590 final long handle = 123456;
4591 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004592 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4593 nullable(EscrowTokenStateChangeCallback.class)))
4594 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004595 assertTrue(dpm.setResetPasswordToken(admin1, token));
4596
4597 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004598 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004599 .thenReturn(true);
4600 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4601
4602 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004603 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4604 eq(LockscreenCredential.createPassword(password)),
4605 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004606 eq(UserHandle.USER_SYSTEM)))
4607 .thenReturn(true);
4608 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4609
4610 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004611 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004612 .thenReturn(true);
4613 assertTrue(dpm.clearResetPasswordToken(admin1));
4614 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004615
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004616 public void testIsActivePasswordSufficient() throws Exception {
4617 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4618 mContext.packageName = admin1.getPackageName();
4619 setupDeviceOwner();
4620
4621 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4622 dpm.setPasswordMinimumLength(admin1, 8);
4623 dpm.setPasswordMinimumLetters(admin1, 6);
4624 dpm.setPasswordMinimumLowerCase(admin1, 3);
4625 dpm.setPasswordMinimumUpperCase(admin1, 1);
4626 dpm.setPasswordMinimumNonLetter(admin1, 1);
4627 dpm.setPasswordMinimumNumeric(admin1, 1);
4628 dpm.setPasswordMinimumSymbols(admin1, 0);
4629
Rubin Xucc391c22018-01-02 20:37:35 +00004630 reset(mContext.spiedContext);
4631
Pavel Grafov6f334842019-08-06 14:37:06 +01004632 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004633
4634 setActivePasswordState(passwordMetricsNoSymbols);
4635 assertTrue(dpm.isActivePasswordSufficient());
4636
4637 initializeDpms();
4638 reset(mContext.spiedContext);
4639 assertTrue(dpm.isActivePasswordSufficient());
4640
4641 // This call simulates the user entering the password for the first time after a reboot.
4642 // This causes password metrics to be reloaded into memory. Until this happens,
4643 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4644 // even if the DPC changes password requirements so that the password no longer meets the
4645 // requirements. This is a known limitation of the current implementation of
4646 // isActivePasswordSufficient() - see b/34218769.
4647 setActivePasswordState(passwordMetricsNoSymbols);
4648 assertTrue(dpm.isActivePasswordSufficient());
4649
4650 dpm.setPasswordMinimumSymbols(admin1, 1);
4651 // This assertion would fail if we had not called setActivePasswordState() again after
4652 // initializeDpms() - see previous comment.
4653 assertFalse(dpm.isActivePasswordSufficient());
4654
4655 initializeDpms();
4656 reset(mContext.spiedContext);
4657 assertFalse(dpm.isActivePasswordSufficient());
4658
Pavel Grafov6f334842019-08-06 14:37:06 +01004659 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004660
4661 setActivePasswordState(passwordMetricsWithSymbols);
4662 assertTrue(dpm.isActivePasswordSufficient());
4663 }
4664
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004665 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4666 // If there is no lock screen, the password is considered empty no matter what, because
4667 // it provides no security.
4668 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4669
4670 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4671 mContext.packageName = admin1.getPackageName();
4672 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004673 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4674 // When there is no lockscreen, user password metrics is always empty.
4675 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004676 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004677
4678 // If no password requirements are set, isActivePasswordSufficient should succeed.
4679 assertTrue(dpm.isActivePasswordSufficient());
4680
4681 // Now set some password quality requirements.
4682 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4683
4684 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004685 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004686 dpm.reportPasswordChanged(userHandle);
4687
4688 // No broadcast should be sent.
4689 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4690 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4691 MockUtils.checkUserHandle(userHandle));
4692
4693 // The active (nonexistent) password doesn't comply with the requirements.
4694 assertFalse(dpm.isActivePasswordSufficient());
4695 }
4696
Pavel Grafov75c0a892017-05-18 17:28:27 +01004697 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4698 throws Exception {
4699 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004700 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004701
Rubin Xu19854862019-08-15 16:37:23 +01004702 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4703 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004704 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004705
Rubin Xucc391c22018-01-02 20:37:35 +00004706 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4707 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004708 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004709 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4710 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004711 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004712 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4713 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004714 // userId, if the password checkpoint value changes.
4715 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4716 MockUtils.checkIntentAction(
4717 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4718 MockUtils.checkUserHandle(userHandle));
4719 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004720 MockUtils.checkIntentAction(
4721 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4722 MockUtils.checkUserHandle(userHandle));
4723
Pavel Grafov75c0a892017-05-18 17:28:27 +01004724 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4725 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004726 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004727
4728 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4729 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004730 MockUtils.checkUserHandle(userHandle),
4731 eq(null),
4732 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004733
4734 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4735 // let it finish with system uid, otherwise it will throw and crash.
4736 flushTasks();
4737
4738 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004739 }
4740
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004741 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4742 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4743 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4744 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4745 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4746 DpmMockContext.SYSTEM_UID);
4747 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4748 DpmMockContext.SYSTEM_UID);
4749
4750 // Set up a device owner.
4751 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004752 setupDeviceOwner();
4753
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004754 // First and second user set IMEs manually.
4755 mContext.binder.callingUid = firstUserSystemUid;
4756 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4757 mContext.binder.callingUid = secondUserSystemUid;
4758 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004759
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004760 // Device owner changes IME for first user.
4761 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004762 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004763 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004764 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004765 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004766 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004767 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004768 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4769 mContext.binder.callingUid = firstUserSystemUid;
4770 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4771 mContext.binder.callingUid = secondUserSystemUid;
4772 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004773
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004774 // Second user changes IME manually.
4775 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4776 mContext.binder.callingUid = firstUserSystemUid;
4777 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4778 mContext.binder.callingUid = secondUserSystemUid;
4779 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004780
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004781 // First user changes IME manually.
4782 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4783 mContext.binder.callingUid = firstUserSystemUid;
4784 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4785 mContext.binder.callingUid = secondUserSystemUid;
4786 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004787
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004788 // Device owner changes IME for first user again.
4789 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004790 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004791 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004792 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004793 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004794 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004795 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4796 mContext.binder.callingUid = firstUserSystemUid;
4797 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4798 mContext.binder.callingUid = secondUserSystemUid;
4799 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004800
4801 // Restarting the DPMS should not lose information.
4802 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004803 mContext.binder.callingUid = firstUserSystemUid;
4804 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4805 mContext.binder.callingUid = secondUserSystemUid;
4806 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004807
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004808 // Device owner can find out whether it set the current IME itself.
4809 mContext.binder.callingUid = deviceOwnerUid;
4810 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004811
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004812 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004813 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004814 mContext.binder.callingUid = firstUserSystemUid;
4815 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4816 mContext.binder.callingUid = secondUserSystemUid;
4817 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004818 }
4819
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004820 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4821 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4822 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4823 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4824 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4825 DpmMockContext.SYSTEM_UID);
4826 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4827 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004828
4829 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004830 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004831 setupProfileOwner();
4832
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004833 // First and second user set IMEs manually.
4834 mContext.binder.callingUid = firstUserSystemUid;
4835 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4836 mContext.binder.callingUid = secondUserSystemUid;
4837 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004838
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004839 // Profile owner changes IME for second user.
4840 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004841 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004842 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004843 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004844 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004845 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004846 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004847 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4848 mContext.binder.callingUid = firstUserSystemUid;
4849 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4850 mContext.binder.callingUid = secondUserSystemUid;
4851 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004852
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004853 // First user changes IME manually.
4854 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4855 mContext.binder.callingUid = firstUserSystemUid;
4856 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4857 mContext.binder.callingUid = secondUserSystemUid;
4858 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004859
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004860 // Second user changes IME manually.
4861 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4862 mContext.binder.callingUid = firstUserSystemUid;
4863 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4864 mContext.binder.callingUid = secondUserSystemUid;
4865 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004866
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004867 // Profile owner changes IME for second user again.
4868 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004869 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004870 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004871 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004872 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004873 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004874 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4875 mContext.binder.callingUid = firstUserSystemUid;
4876 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4877 mContext.binder.callingUid = secondUserSystemUid;
4878 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004879
4880 // Restarting the DPMS should not lose information.
4881 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004882 mContext.binder.callingUid = firstUserSystemUid;
4883 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4884 mContext.binder.callingUid = secondUserSystemUid;
4885 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004886
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004887 // Profile owner can find out whether it set the current IME itself.
4888 mContext.binder.callingUid = profileOwnerUid;
4889 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004890
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004891 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004892 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004893 mContext.binder.callingUid = firstUserSystemUid;
4894 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4895 mContext.binder.callingUid = secondUserSystemUid;
4896 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004897 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004898
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004899 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4900 throws Exception {
4901 // Set up a device owner.
4902 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4903 setupDeviceOwner();
4904 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4905 }
4906
4907 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4908 throws Exception {
4909 // Set up a profile owner.
4910 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4911 setupProfileOwner();
4912 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4913 }
4914
4915 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4916 int adminUid) throws Exception {
4917 mContext.binder.callingUid = adminUid;
4918 final int userId = UserHandle.getUserId(adminUid);
4919
4920 final String packageName = "some.package";
4921 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4922 admin1, Collections.singletonList(packageName)));
4923 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4924
4925 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4926 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4927
4928 // Attempt to set to empty list (which means no listener is whitelisted)
4929 mContext.binder.callingUid = adminUid;
4930 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004931 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004932 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4933
4934 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4935 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4936 }
4937
4938 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4939 // Set up a managed profile
4940 final int MANAGED_PROFILE_USER_ID = 15;
4941 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4942 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4943 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4944
4945 final String permittedListener = "some.package";
4946 setupPackageInPackageManager(
4947 permittedListener,
4948 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4949 /*appId=*/ 12345, /*flags=*/ 0);
4950
4951 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4952 admin1, Collections.singletonList(permittedListener)));
4953
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004954 // isNotificationListenerServicePermitted should throw if not called from System.
4955 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4956 () -> dpms.isNotificationListenerServicePermitted(
4957 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004958
4959 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4960 assertTrue(dpms.isNotificationListenerServicePermitted(
4961 permittedListener, MANAGED_PROFILE_USER_ID));
4962 }
4963
4964 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4965 throws Exception {
4966 // Set up a managed profile
4967 final int MANAGED_PROFILE_USER_ID = 15;
4968 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4969 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4970 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4971
4972 final String permittedListener = "permitted.package";
4973 int appId = 12345;
4974 setupPackageInPackageManager(
4975 permittedListener,
4976 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4977 appId, /*flags=*/ 0);
4978
4979 final String notPermittedListener = "not.permitted.package";
4980 setupPackageInPackageManager(
4981 notPermittedListener,
4982 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4983 ++appId, /*flags=*/ 0);
4984
4985 final String systemListener = "system.package";
4986 setupPackageInPackageManager(
4987 systemListener,
4988 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4989 ++appId, ApplicationInfo.FLAG_SYSTEM);
4990
4991 // By default all packages are allowed
4992 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4993
4994 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4995 assertTrue(dpms.isNotificationListenerServicePermitted(
4996 permittedListener, MANAGED_PROFILE_USER_ID));
4997 assertTrue(dpms.isNotificationListenerServicePermitted(
4998 notPermittedListener, MANAGED_PROFILE_USER_ID));
4999 assertTrue(dpms.isNotificationListenerServicePermitted(
5000 systemListener, MANAGED_PROFILE_USER_ID));
5001
5002 // Setting only one package in the whitelist
5003 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5004 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
5005 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005006 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005007 dpms.getPermittedCrossProfileNotificationListeners(admin1);
5008 assertEquals(1, permittedListeners.size());
5009 assertEquals(permittedListener, permittedListeners.get(0));
5010
5011 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5012 assertTrue(dpms.isNotificationListenerServicePermitted(
5013 permittedListener, MANAGED_PROFILE_USER_ID));
5014 assertFalse(dpms.isNotificationListenerServicePermitted(
5015 notPermittedListener, MANAGED_PROFILE_USER_ID));
5016 // System packages are always allowed (even if not in the whitelist)
5017 assertTrue(dpms.isNotificationListenerServicePermitted(
5018 systemListener, MANAGED_PROFILE_USER_ID));
5019
5020 // Setting an empty whitelist - only system listeners allowed
5021 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5022 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005023 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005024 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5025
5026 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5027 assertFalse(dpms.isNotificationListenerServicePermitted(
5028 permittedListener, MANAGED_PROFILE_USER_ID));
5029 assertFalse(dpms.isNotificationListenerServicePermitted(
5030 notPermittedListener, MANAGED_PROFILE_USER_ID));
5031 // System packages are always allowed (even if not in the whitelist)
5032 assertTrue(dpms.isNotificationListenerServicePermitted(
5033 systemListener, MANAGED_PROFILE_USER_ID));
5034
5035 // Setting a null whitelist - all listeners allowed
5036 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5037 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
5038 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5039
5040 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5041 assertTrue(dpms.isNotificationListenerServicePermitted(
5042 permittedListener, MANAGED_PROFILE_USER_ID));
5043 assertTrue(dpms.isNotificationListenerServicePermitted(
5044 notPermittedListener, MANAGED_PROFILE_USER_ID));
5045 assertTrue(dpms.isNotificationListenerServicePermitted(
5046 systemListener, MANAGED_PROFILE_USER_ID));
5047 }
5048
5049 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
5050 throws Exception {
5051 // Set up a managed profile
5052 final int MANAGED_PROFILE_USER_ID = 15;
5053 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5054 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5055 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5056
5057 final String nonSystemPackage = "non.system.package";
5058 int appId = 12345;
5059 setupPackageInPackageManager(
5060 nonSystemPackage,
5061 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5062 appId, /*flags=*/ 0);
5063
5064 final String systemListener = "system.package";
5065 setupPackageInPackageManager(
5066 systemListener,
5067 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5068 ++appId, ApplicationInfo.FLAG_SYSTEM);
5069
5070 // By default all packages are allowed (for all profiles)
5071 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5072
5073 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5074 assertTrue(dpms.isNotificationListenerServicePermitted(
5075 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5076 assertTrue(dpms.isNotificationListenerServicePermitted(
5077 systemListener, MANAGED_PROFILE_USER_ID));
5078 assertTrue(dpms.isNotificationListenerServicePermitted(
5079 nonSystemPackage, UserHandle.USER_SYSTEM));
5080 assertTrue(dpms.isNotificationListenerServicePermitted(
5081 systemListener, UserHandle.USER_SYSTEM));
5082
5083 // Setting an empty whitelist - only system listeners allowed in managed profile, but
5084 // all allowed in primary profile
5085 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5086 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005087 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005088 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5089
5090 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5091 assertFalse(dpms.isNotificationListenerServicePermitted(
5092 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5093 assertTrue(dpms.isNotificationListenerServicePermitted(
5094 systemListener, MANAGED_PROFILE_USER_ID));
5095 assertTrue(dpms.isNotificationListenerServicePermitted(
5096 nonSystemPackage, UserHandle.USER_SYSTEM));
5097 assertTrue(dpms.isNotificationListenerServicePermitted(
5098 systemListener, UserHandle.USER_SYSTEM));
5099 }
5100
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005101 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005102 mServiceContext.packageName = mRealTestContext.getPackageName();
5103 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5104 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005105 setDeviceOwner();
5106
Pavel Grafov75c0a892017-05-18 17:28:27 +01005107 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005108 }
5109
5110 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005111 mServiceContext.packageName = mRealTestContext.getPackageName();
5112 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5113 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005114 setAsProfileOwner(admin1);
5115
Pavel Grafov75c0a892017-05-18 17:28:27 +01005116 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
5117 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005118 }
5119
5120 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005121 mServiceContext.packageName = mRealTestContext.getPackageName();
5122 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5123 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005124 setAsProfileOwner(admin1);
5125
Pavel Grafov75c0a892017-05-18 17:28:27 +01005126 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
5127 caller.packageName = "com.example.delegate";
5128 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
5129 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005130
Pavel Grafov75c0a892017-05-18 17:28:27 +01005131 // Make caller a delegated cert installer.
5132 runAsCaller(mAdmin1Context, dpms,
5133 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00005134
5135 verifyCanGetOwnerInstalledCaCerts(null, caller);
5136 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005137 }
5138
Rubin Xucc391c22018-01-02 20:37:35 +00005139 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005140 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5141 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005142 Bundle restriction = new Bundle();
5143 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5144
5145 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5146 RestrictionsListener listener = new RestrictionsListener(mContext);
5147 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
5148 new Bundle());
5149 verifyDataSharingChangedBroadcast();
5150 }
5151
5152 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005153 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5154 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005155 Bundle restriction = new Bundle();
5156 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5157
5158 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5159 RestrictionsListener listener = new RestrictionsListener(mContext);
5160 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5161 restriction);
5162 verifyDataSharingChangedBroadcast();
5163 }
5164
5165 public void testDisallowSharingIntoProfileUnchanged() {
5166 RestrictionsListener listener = new RestrictionsListener(mContext);
5167 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5168 new Bundle());
5169 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
5170 }
5171
5172 private void verifyDataSharingChangedBroadcast() {
5173 Intent expectedIntent = new Intent(
5174 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
5175 expectedIntent.setPackage("com.android.managedprovisioning");
5176 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
5177 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
5178 MockUtils.checkIntent(expectedIntent),
5179 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
5180 }
5181
yuemingwe3d9c092018-01-11 12:11:44 +00005182 public void testOverrideApnAPIsFailWithPO() throws Exception {
5183 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00005184 ApnSetting apn = (new ApnSetting.Builder())
5185 .setApnName("test")
5186 .setEntryName("test")
5187 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
5188 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00005189 assertExpectException(SecurityException.class, null, () ->
5190 dpm.addOverrideApn(admin1, apn));
5191 assertExpectException(SecurityException.class, null, () ->
5192 dpm.updateOverrideApn(admin1, 0, apn));
5193 assertExpectException(SecurityException.class, null, () ->
5194 dpm.removeOverrideApn(admin1, 0));
5195 assertExpectException(SecurityException.class, null, () ->
5196 dpm.getOverrideApns(admin1));
5197 assertExpectException(SecurityException.class, null, () ->
5198 dpm.setOverrideApnsEnabled(admin1, false));
5199 assertExpectException(SecurityException.class, null, () ->
5200 dpm.isOverrideApnEnabled(admin1));
5201 }
5202
Robin Lee2c68dad2017-03-17 12:50:24 +00005203 private void verifyCanGetOwnerInstalledCaCerts(
5204 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005205 final String alias = "cert";
5206 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005207
5208 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005209 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005210 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5211 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005212 }
5213 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5214
5215 // caller: device admin or delegated certificate installer
5216 callerContext.applicationInfo = new ApplicationInfo();
5217 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5218
5219 // system_server
5220 final DpmMockContext serviceContext = mContext;
5221 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005222 getServices().addPackageContext(callerUser, admin1Context);
5223 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005224
5225 // Install a CA cert.
5226 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005227 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005228 .thenReturn(alias);
5229 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005230 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00005231 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00005232 });
5233
Pavel Grafov75c0a892017-05-18 17:28:27 +01005234 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5235 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5236 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005237 flushTasks();
5238
Robin Lee2c68dad2017-03-17 12:50:24 +00005239 final List<String> ownerInstalledCaCerts = new ArrayList<>();
5240
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005241 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00005242 runAsCaller(admin1Context, dpms, (dpm) -> {
5243 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005244 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00005245 ownerInstalledCaCerts.addAll(installedCaCerts);
5246 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005247
5248 // Restarting the DPMS should not lose information.
5249 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01005250 runAsCaller(admin1Context, dpms, (dpm) ->
5251 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005252
5253 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005254 runAsCaller(serviceContext, dpms, (dpm) -> {
5255 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005256
Robin Lee2c68dad2017-03-17 12:50:24 +00005257 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005258 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00005259 });
5260
Pavel Grafov75c0a892017-05-18 17:28:27 +01005261 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5262 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5263 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005264 flushTasks();
5265
5266 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
5267 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005268 runAsCaller(admin1Context, dpms, (dpm) -> {
5269 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
5270 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005271 }
5272
Robin Lee2c68dad2017-03-17 12:50:24 +00005273 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
5274 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005275 final String alias = "cert";
5276 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005277
5278 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005279 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005280 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5281 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005282 }
5283 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5284
5285 // caller: device admin or delegated certificate installer
5286 callerContext.applicationInfo = new ApplicationInfo();
5287 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5288
5289 // system_server
5290 final DpmMockContext serviceContext = mContext;
5291 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005292 getServices().addPackageContext(callerUser, admin1Context);
5293 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005294
5295 // Install a CA cert as caller
5296 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005297 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005298 .thenReturn(alias);
5299 assertTrue(dpm.installCaCert(callerName, caCert));
5300 });
5301
5302 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005303 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005304 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005305 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5306 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5307 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005308 flushTasks();
5309
Robin Lee2c68dad2017-03-17 12:50:24 +00005310 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005311 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005312
5313 runAsCaller(serviceContext, dpms, (dpm) -> {
5314 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5315 assertNotNull(ownerInstalledCaCerts);
5316 assertTrue(ownerInstalledCaCerts.isEmpty());
5317 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005318 }
5319
Eran Messeri94d56762017-12-21 20:50:54 +00005320 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5321 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5322 Arrays.sort(gotFlags);
5323 Arrays.sort(expectedFlags);
5324 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5325 }
5326
5327 public void testTranslationOfIdAttestationFlag() {
5328 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5329 int[] correspondingAttUtilsTypes = new int[]{
5330 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5331 AttestationUtils.ID_TYPE_MEID};
5332
5333 // Test translation of zero flags
5334 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5335
5336 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5337 // non-null array
5338 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5339
5340 // Test translation of a single flag
5341 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5342 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5343 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5344
5345 // Test translation of two flags
5346 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5347 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5348 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5349 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5350
5351 // Test translation of all three flags
5352 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5353 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5354 AttestationUtils.ID_TYPE_MEID});
5355 // Test translation of all three flags
5356 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5357 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5358 AttestationUtils.ID_TYPE_MEID});
5359 }
5360
arangelov08d534b2018-01-22 15:20:53 +00005361 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5362 setDeviceOwner();
5363 initializeDpms();
5364 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5365 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5366 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5367 }
5368
5369 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5370 DpmTestUtils.writeInputStreamToFile(
5371 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5372 getDeviceOwnerPoliciesFile());
5373 DpmTestUtils.writeInputStreamToFile(
5374 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5375 getDeviceOwnerFile());
5376 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5377 }
5378
5379 public void testRevertDeviceOwnership_deviceNotMigrated()
5380 throws Exception {
5381 DpmTestUtils.writeInputStreamToFile(
5382 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5383 getDeviceOwnerPoliciesFile());
5384 DpmTestUtils.writeInputStreamToFile(
5385 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5386 getDeviceOwnerFile());
5387 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5388 }
5389
5390 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5391 throws Exception {
5392 DpmTestUtils.writeInputStreamToFile(
5393 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5394 getDeviceOwnerPoliciesFile());
5395 DpmTestUtils.writeInputStreamToFile(
5396 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5397 getDeviceOwnerFile());
5398 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5399 }
5400
5401 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5402 setupProfileOwner();
5403 initializeDpms();
5404 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5405 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5406 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5407 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5408 }
5409
5410 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005411 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5412 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005413 DpmTestUtils.writeInputStreamToFile(
5414 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5415 getProfileOwnerPoliciesFile());
5416 DpmTestUtils.writeInputStreamToFile(
5417 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5418 getProfileOwnerFile());
5419 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5420 }
5421
5422 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005423 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5424 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005425 DpmTestUtils.writeInputStreamToFile(
5426 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5427 getProfileOwnerPoliciesFile());
5428 DpmTestUtils.writeInputStreamToFile(
5429 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5430 getProfileOwnerFile());
5431 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5432 }
5433
5434 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005435 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5436 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005437 DpmTestUtils.writeInputStreamToFile(
5438 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5439 getProfileOwnerPoliciesFile());
5440 DpmTestUtils.writeInputStreamToFile(
5441 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5442 getProfileOwnerFile());
5443 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5444 }
5445
Eran Messeribb271892018-10-17 18:27:50 +01005446 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5447 setupProfileOwner();
5448 configureContextForAccess(mContext, false);
5449
5450 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005451 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005452 }
5453
5454 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5455 setupProfileOwner();
5456 configureContextForAccess(mContext, false);
5457
5458 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005459 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005460 }
5461
5462 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5463 setupProfileOwner();
5464
5465 // This method will throw if the system context could not call
Eran Messeri18d21312019-11-14 22:44:40 +00005466 // markProfileOwnerOfOrganizationOwnedDevice successfully.
5467 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005468 }
5469
Eran Messerib8c46e02019-11-07 12:06:18 +00005470 private void configureContextForAccess(DpmMockContext context, boolean granted) {
Eran Messeribb271892018-10-17 18:27:50 +01005471 when(context.spiedContext.checkCallingPermission(
Eran Messeri18d21312019-11-14 22:44:40 +00005472 permission.MARK_DEVICE_ORGANIZATION_OWNED))
Eran Messeribb271892018-10-17 18:27:50 +01005473 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5474 : PackageManager.PERMISSION_DENIED);
Eran Messerib8c46e02019-11-07 12:06:18 +00005475
5476 when(getServices().userManager.getProfileParent(any()))
5477 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005478 }
5479
5480 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5481 setupProfileOwner();
5482
5483 final long ident = mServiceContext.binder.clearCallingIdentity();
5484 configureContextForAccess(mServiceContext, true);
5485
5486 mServiceContext.binder.callingUid =
5487 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5488 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5489 try {
5490 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005491 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005492 });
5493 } finally {
5494 mServiceContext.binder.restoreCallingIdentity(ident);
5495 }
5496 }
5497
5498 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5499 throws Exception {
5500 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5501 setupDeviceOwner();
5502 configureContextForAccess(mContext, false);
5503
5504 // Device owner should be allowed to request Device ID attestation.
5505 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5506 DpmMockContext.CALLER_SYSTEM_USER_UID);
5507
5508 // Another package must not be allowed to request Device ID attestation.
5509 assertExpectException(SecurityException.class, null,
5510 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5511 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5512 // Another component that is not the admin must not be allowed to request Device ID
5513 // attestation.
5514 assertExpectException(SecurityException.class, null,
5515 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5516 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5517 }
5518
5519 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5520 throws Exception {
5521 configureContextForAccess(mContext, false);
5522
5523 // Make sure a security exception is thrown if the device has no profile owner.
5524 assertExpectException(SecurityException.class, null,
5525 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5526 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5527
5528 setupProfileOwner();
Eran Messeri18d21312019-11-14 22:44:40 +00005529 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005530
5531 // The profile owner is allowed to request Device ID attestation.
5532 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5533 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5534 DpmMockContext.CALLER_UID);
5535 // But not another package.
5536 assertExpectException(SecurityException.class, null,
5537 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5538 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5539 // Or another component which is not the admin.
5540 assertExpectException(SecurityException.class, null,
5541 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5542 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5543 }
5544
5545 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5546 final long ident = mServiceContext.binder.clearCallingIdentity();
5547
5548 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5549 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5550 try {
5551 runAsCaller(mServiceContext, dpms, action);
5552 } finally {
5553 mServiceContext.binder.restoreCallingIdentity(ident);
5554 }
5555 }
5556
5557 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5558 setupProfileOwner();
5559 markDelegatedCertInstallerAsInstalled();
5560
5561 // Configure a delegated cert installer.
5562 runAsCaller(mServiceContext, dpms,
5563 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5564 Arrays.asList(DELEGATION_CERT_INSTALL)));
5565
Eran Messeri18d21312019-11-14 22:44:40 +00005566 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005567
5568 // Make sure that the profile owner can still request Device ID attestation.
5569 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5570 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5571 DpmMockContext.CALLER_UID);
5572
5573 runAsDelegatedCertInstaller(dpm -> {
5574 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5575 DpmMockContext.DELEGATE_PACKAGE_NAME,
5576 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5577 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5578 });
5579 }
5580
5581 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5582 throws Exception {
5583 setupProfileOwner();
5584 markDelegatedCertInstallerAsInstalled();
5585
5586 // Configure a delegated cert installer.
5587 runAsCaller(mServiceContext, dpms,
5588 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5589 Arrays.asList(DELEGATION_CERT_INSTALL)));
5590
5591
5592 assertExpectException(SecurityException.class, null,
5593 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5594 admin1.getPackageName(),
5595 DpmMockContext.CALLER_UID));
5596
5597 runAsDelegatedCertInstaller(dpm -> {
5598 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5599 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5600 DpmMockContext.DELEGATE_PACKAGE_NAME,
5601 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5602 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5603 });
5604 }
5605
Alex Johnston07cb9f02019-11-01 17:40:38 +00005606 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
5607 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5608 setAsProfileOwner(admin1);
5609
Alex Johnston755e3772019-11-29 03:27:22 +00005610 parentDpm.getPasswordComplexity();
Alex Johnston07cb9f02019-11-01 17:40:38 +00005611
5612 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005613 }
5614
5615 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5616 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5617 .thenReturn(false);
5618 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5619 }
5620
5621 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5622 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5623 .thenReturn(true);
5624 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5625 }
5626
5627
5628 public void testGetPasswordComplexity_currentUserNoPassword() {
5629 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5630 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005631 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005632 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5633 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5634
5635 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5636 }
5637
5638 public void testGetPasswordComplexity_currentUserHasPassword() {
5639 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5640 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005641 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005642 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5643 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005644 when(getServices().lockSettingsInternal
5645 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005646 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005647
5648 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5649 }
5650
5651 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5652 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5653 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005654 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005655
5656 UserInfo parentUser = new UserInfo();
5657 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5658 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5659 .thenReturn(parentUser.id);
5660
Rubin Xu19854862019-08-15 16:37:23 +01005661 when(getServices().lockSettingsInternal
5662 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005663 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005664 when(getServices().lockSettingsInternal
5665 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005666 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005667
5668 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5669 }
5670
yuemingwd2bfbc82019-01-02 11:42:25 +00005671 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5672 setAsProfileOwner(admin1);
5673 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5674 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5675 }
5676
5677 public void testCrossProfileCalendarPackages_reopenDpms() {
5678 setAsProfileOwner(admin1);
5679 dpm.setCrossProfileCalendarPackages(admin1, null);
5680 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5681 assertTrue(packages == null);
5682 initializeDpms();
5683 packages = dpm.getCrossProfileCalendarPackages(admin1);
5684 assertTrue(packages == null);
5685
5686 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5687 packages = dpm.getCrossProfileCalendarPackages(admin1);
5688 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5689 initializeDpms();
5690 packages = dpm.getCrossProfileCalendarPackages(admin1);
5691 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5692
5693 final String dummyPackageName = "test";
5694 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5695 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5696 packages = dpm.getCrossProfileCalendarPackages(admin1);
5697 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5698 initializeDpms();
5699 packages = dpm.getCrossProfileCalendarPackages(admin1);
5700 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5701 }
5702
5703 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5704 assertTrue(expected != null);
5705 assertTrue(actual != null);
5706 assertTrue(expected.containsAll(actual));
5707 assertTrue(actual.containsAll(expected));
5708 }
5709
yuemingwdded98f2019-01-30 17:08:12 +00005710 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5711 setAsProfileOwner(admin1);
5712 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5713 when(getServices().settings.settingsSecureGetIntForUser(
5714 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5715 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5716 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5717 }
5718
5719 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5720 final String testPackage = "TEST_PACKAGE";
5721 setAsProfileOwner(admin1);
5722 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5723 when(getServices().settings.settingsSecureGetIntForUser(
5724 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5725 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5726 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5727 }
5728
5729 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5730 final String testPackage = "TEST_PACKAGE";
5731 setAsProfileOwner(admin1);
5732 dpm.setCrossProfileCalendarPackages(admin1, null);
5733 when(getServices().settings.settingsSecureGetIntForUser(
5734 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5735 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5736 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5737 }
5738
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005739 public void testSetProtectedPackages_asDO() throws Exception {
5740 final List<String> testPackages = new ArrayList<>();
5741 testPackages.add("package_1");
5742 testPackages.add("package_2");
5743
5744 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5745 setDeviceOwner();
5746
5747 dpm.setProtectedPackages(admin1, testPackages);
5748
5749 verify(getServices().packageManagerInternal).setDeviceOwnerProtectedPackages(testPackages);
5750
5751 assertEquals(testPackages, dpm.getProtectedPackages(admin1));
5752 }
5753
5754 public void testSetProtectedPackages_failingAsPO() throws Exception {
5755 final List<String> testPackages = new ArrayList<>();
5756 testPackages.add("package_1");
5757 testPackages.add("package_2");
5758
5759 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5760 setAsProfileOwner(admin1);
5761
5762 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5763 () -> dpm.setProtectedPackages(admin1, testPackages));
5764
5765 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5766 () -> dpm.getProtectedPackages(admin1));
5767 }
5768
Eran Messeri18d21312019-11-14 22:44:40 +00005769 private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
Eran Messerib8c46e02019-11-07 12:06:18 +00005770 when(getServices().userManager.getProfileParent(eq(UserHandle.of(userId))))
5771 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005772 final long ident = mServiceContext.binder.clearCallingIdentity();
5773 mServiceContext.binder.callingUid =
5774 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
Eran Messeri18d21312019-11-14 22:44:40 +00005775
5776 configureContextForAccess(mServiceContext, true);
Eran Messeribb271892018-10-17 18:27:50 +01005777 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005778 dpm.markProfileOwnerOnOrganizationOwnedDevice(who);
Eran Messeribb271892018-10-17 18:27:50 +01005779 });
5780 mServiceContext.binder.restoreCallingIdentity(ident);
5781 }
5782
Alex Kershaw434a2242019-12-04 11:34:45 +00005783 public void testGetCrossProfilePackages_notSet_returnsEmpty() {
5784 setAsProfileOwner(admin1);
5785 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
5786 }
5787
5788 public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() {
5789 setAsProfileOwner(admin1);
5790
5791 initializeDpms();
5792
5793 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
5794 }
5795
5796 public void testGetCrossProfilePackages_whenSet_returnsEqual() {
5797 setAsProfileOwner(admin1);
5798 Set<String> packages = Collections.singleton("TEST_PACKAGE");
5799
5800 dpm.setCrossProfilePackages(admin1, packages);
5801
5802 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
5803 }
5804
5805 public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() {
5806 setAsProfileOwner(admin1);
5807 Set<String> packages = Collections.singleton("TEST_PACKAGE");
5808
5809 dpm.setCrossProfilePackages(admin1, packages);
5810 initializeDpms();
5811
5812 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
5813 }
5814
kholoud mohamedfff05762019-12-10 11:38:04 +00005815 public void testGetAllCrossProfilePackages_notSet_returnsEmpty() throws Exception {
5816 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00005817 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005818
5819 setCrossProfileAppsList();
5820
5821 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
5822 }
5823
5824 public void testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()
5825 throws Exception {
5826 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00005827 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005828
5829 setCrossProfileAppsList();
5830 initializeDpms();
5831
5832 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
5833 }
5834
5835 public void testGetAllCrossProfilePackages_whenSet_returnsCombinedSet() throws Exception {
5836 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
5837 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00005838 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005839
5840 dpm.setCrossProfilePackages(admin1, packages);
5841 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
5842
5843 assertEquals(Sets.newSet(
5844 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"),
5845 dpm.getAllCrossProfilePackages());
5846
5847 }
5848
5849 public void testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet()
5850 throws Exception {
5851 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
5852 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00005853 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005854
5855 dpm.setCrossProfilePackages(admin1, packages);
5856 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
5857 initializeDpms();
5858
5859 assertEquals(Sets.newSet(
5860 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"),
5861 dpm.getAllCrossProfilePackages());
5862 }
5863
Rubin Xu41bdd972020-01-03 17:18:33 +00005864 public void testSetCommonCriteriaMode_asDeviceOwner() throws Exception {
5865 setDeviceOwner();
5866
5867 dpm.setCommonCriteriaModeEnabled(admin1, true);
5868 verify(getServices().settings).settingsGlobalPutInt(
5869 Settings.Global.COMMON_CRITERIA_MODE, 1);
5870
5871 when(getServices().settings.settingsGlobalGetInt(Settings.Global.COMMON_CRITERIA_MODE, 0))
5872 .thenReturn(1);
5873 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
5874 }
5875
5876 public void testSetCommonCriteriaMode_asPoOfOrgOwnedDevice() throws Exception {
5877 setupProfileOwner();
5878 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
5879
5880 dpm.setCommonCriteriaModeEnabled(admin1, true);
5881 verify(getServices().settings).settingsGlobalPutInt(
5882 Settings.Global.COMMON_CRITERIA_MODE, 1);
5883
5884 when(getServices().settings.settingsGlobalGetInt(Settings.Global.COMMON_CRITERIA_MODE, 0))
5885 .thenReturn(1);
5886 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
5887 }
5888
kholoud mohamedfff05762019-12-10 11:38:04 +00005889 private void setCrossProfileAppsList(String... packages) {
5890 when(mContext.getResources()
5891 .getStringArray(eq(R.array.cross_profile_apps)))
5892 .thenReturn(packages);
5893 }
5894
arangelov08d534b2018-01-22 15:20:53 +00005895 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5896 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5897 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5898 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5899
5900 final long ident = mServiceContext.binder.clearCallingIdentity();
5901 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5902 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5903 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5904 // To simulate a reboot, we just reinitialize dpms and call systemReady
5905 initializeDpms();
5906
5907 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5908 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5909 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5910 assertTrue(dpm.isAdminActive(admin1));
5911 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5912 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5913
5914 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5915 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5916 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5917 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5918
5919 mServiceContext.binder.restoreCallingIdentity(ident);
5920 }
5921
5922 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5923 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5924 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5925 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5926
5927 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5928 DpmMockContext.CALLER_SYSTEM_USER_UID);
5929 setUpPackageManagerForAdmin(admin1, uid);
5930 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5931 // To simulate a reboot, we just reinitialize dpms and call systemReady
5932 initializeDpms();
5933
5934 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5935 assertTrue(dpm.isAdminActive(admin1));
5936 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5937 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5938 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5939 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5940 }
5941
5942 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5943 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5944 metadataManager.deleteMetadataFile();
5945
5946 final TransferOwnershipMetadataManager.Metadata metadata =
5947 new TransferOwnershipMetadataManager.Metadata(
5948 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5949 callerUserHandle,
5950 adminType);
5951 metadataManager.saveMetadataFile(metadata);
5952 }
5953
5954 private File getDeviceOwnerFile() {
5955 return dpms.mOwners.getDeviceOwnerFile();
5956 }
5957
5958 private File getProfileOwnerFile() {
5959 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5960 }
5961
5962 private File getProfileOwnerPoliciesFile() {
5963 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5964 DpmMockContext.CALLER_USER_HANDLE);
5965 return getPoliciesFile(parentDir);
5966 }
5967
5968 private File getDeviceOwnerPoliciesFile() {
5969 return getPoliciesFile(getServices().systemUserDataDir);
5970 }
5971
5972 private File getPoliciesFile(File parentDir) {
5973 return new File(parentDir, "device_policies.xml");
5974 }
5975
Victor Chang3e794af2016-03-04 13:48:17 +00005976 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005977 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005978 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5979 dpms.notifyChangeToContentObserver(
5980 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5981 }
5982
5983 private void assertProvisioningAllowed(String action, boolean expected) {
5984 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5985 dpm.isProvisioningAllowed(action));
5986 }
Tony Mak2f26b792016-11-28 17:54:51 +00005987
Nicolas Prevot45d29072017-01-18 16:11:19 +00005988 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5989 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005990 final String previousPackageName = mContext.packageName;
5991 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005992
5993 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5994 mContext.packageName = packageName;
5995 mMockContext.binder.callingUid = uid;
5996 assertProvisioningAllowed(action, expected);
5997
5998 // Set the previous package name / calling uid to go back to the initial state.
5999 mContext.packageName = previousPackageName;
6000 mMockContext.binder.callingUid = previousUid;
6001 }
6002
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006003 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00006004 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
6005 }
6006
6007 private void assertCheckProvisioningPreCondition(
6008 String action, String packageName, int provisioningCondition) {
6009 assertEquals("checkProvisioningPreCondition("
6010 + action + ", " + packageName + ") returning unexpected result",
6011 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006012 }
6013
Tony Mak2f26b792016-11-28 17:54:51 +00006014 /**
6015 * Setup a managed profile with the specified admin and its uid.
6016 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
6017 * @param adminUid uid of the admin package.
6018 * @param copyFromAdmin package information for {@code admin} will be built based on this
6019 * component's information.
6020 */
6021 private void addManagedProfile(
6022 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
6023 final int userId = UserHandle.getUserId(adminUid);
Alex Johnston755e3772019-11-29 03:27:22 +00006024 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
6025 UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00006026 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
6027 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
6028 dpm.setActiveAdmin(admin, false, userId);
6029 assertTrue(dpm.setProfileOwner(admin, null, userId));
6030 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
6031 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00006032
6033 /**
Robin Leeabaa0692017-02-20 20:54:22 +00006034 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00006035 */
Robin Leeabaa0692017-02-20 20:54:22 +00006036 private static StringParceledListSlice asSlice(String[] s) {
6037 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00006038 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006039
6040 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00006041 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
6042 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006043
Robin Lee2c68dad2017-03-17 12:50:24 +00006044 // We can't let exceptions happen on the background thread. Throw them here if they happen
6045 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01006046 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006047 }
Victor Chang3e794af2016-03-04 13:48:17 +00006048}