blob: 422c278a3af70ddaee301b9e30b4d391db83636d [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,
Alex Johnston9722abe2020-01-28 16:15:55 +00001989 UserManager.DISALLOW_USB_FILE_TRANSFER,
1990 UserManager.DISALLOW_AIRPLANE_MODE,
1991 UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA,
1992 UserManager.DISALLOW_OUTGOING_CALLS,
1993 UserManager.DISALLOW_UNMUTE_MICROPHONE
Alex Johnston7c3d7e22020-01-08 12:57:14 +00001994 );
1995
Alex Johnstonece5cdb2019-11-20 14:37:13 +00001996 public void testSetUserRestriction_asPoOfOrgOwnedDevice() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00001997 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
1998 final int MANAGED_PROFILE_ADMIN_UID =
1999 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2000 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002001
Alex Johnston755e3772019-11-29 03:27:22 +00002002 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2003 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002004
Alex Johnston755e3772019-11-29 03:27:22 +00002005 when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2006 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002007
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002008 for (String restriction : PROFILE_OWNER_ORGANIZATION_OWNED_GLOBAL_RESTRICTIONS) {
2009 addAndRemoveUserRestrictionOnParentDpm(restriction);
2010 }
Alex Johnston51419382019-11-26 17:00:10 +00002011
Alex Johnston755e3772019-11-29 03:27:22 +00002012 parentDpm.setCameraDisabled(admin1, true);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002013 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnston51419382019-11-26 17:00:10 +00002014 eq(MANAGED_PROFILE_USER_ID),
Alex Johnston755e3772019-11-29 03:27:22 +00002015 MockUtils.checkUserRestrictions(UserManager.DISALLOW_CAMERA),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002016 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2017 reset(getServices().userManagerInternal);
2018
Alex Johnston755e3772019-11-29 03:27:22 +00002019 parentDpm.setCameraDisabled(admin1, false);
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002020 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Alex Johnston51419382019-11-26 17:00:10 +00002021 eq(MANAGED_PROFILE_USER_ID),
Alex Johnston755e3772019-11-29 03:27:22 +00002022 MockUtils.checkUserRestrictions(),
Alex Johnstonece5cdb2019-11-20 14:37:13 +00002023 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2024 reset(getServices().userManagerInternal);
2025 }
Esteban Talavera548a04b2016-12-20 15:22:30 +00002026
Alex Johnston7c3d7e22020-01-08 12:57:14 +00002027 private void addAndRemoveUserRestrictionOnParentDpm(String restriction) {
2028 parentDpm.addUserRestriction(admin1, restriction);
2029 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
2030 eq(DpmMockContext.CALLER_USER_HANDLE),
2031 MockUtils.checkUserRestrictions(restriction),
2032 eq(UserManagerInternal.OWNER_TYPE_PROFILE_OWNER_OF_ORGANIZATION_OWNED_DEVICE));
2033 parentDpm.clearUserRestriction(admin1, restriction);
2034 DpmTestUtils.assertRestrictions(
2035 DpmTestUtils.newRestrictions(),
2036 parentDpm.getUserRestrictions(admin1)
2037 );
2038 reset(getServices().userManagerInternal);
2039 }
2040
Eran Messerice273df2019-12-17 13:14:45 +00002041 public void testNoDefaultEnabledUserRestrictions() throws Exception {
Esteban Talavera548a04b2016-12-20 15:22:30 +00002042 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2043 mContext.callerPermissions.add(permission.MANAGE_USERS);
2044 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2045 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2046
2047 // First, set DO.
2048
2049 // Call from a process on the system user.
2050 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2051
2052 // Make sure admin1 is installed on system user.
2053 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2054
2055 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
2056 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
2057 UserHandle.USER_SYSTEM));
2058
Esteban Talavera548a04b2016-12-20 15:22:30 +00002059 assertNoDeviceOwnerRestrictions();
2060
Pavel Grafov75c0a892017-05-18 17:28:27 +01002061 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002062
Eran Messeri6ad0e192019-12-01 20:01:21 +00002063 // Ensure the DISALLOW_REMOVE_MANAGED_PROFILES restriction doesn't show up as a
2064 // restriction to the device owner.
2065 dpm.addUserRestriction(admin1, UserManager.DISALLOW_REMOVE_MANAGED_PROFILE);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002066 assertNoDeviceOwnerRestrictions();
Esteban Talavera548a04b2016-12-20 15:22:30 +00002067 }
2068
2069 private void assertNoDeviceOwnerRestrictions() {
2070 DpmTestUtils.assertRestrictions(
2071 DpmTestUtils.newRestrictions(),
2072 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2073 );
2074 DpmTestUtils.assertRestrictions(
2075 DpmTestUtils.newRestrictions(),
2076 dpm.getUserRestrictions(admin1)
2077 );
2078 }
2079
Alex Johnston011f5c62019-12-18 17:05:57 +00002080 public void testSetFactoryResetProtectionPolicyWithDO() throws Exception {
2081 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2082 setupDeviceOwner();
2083
2084 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2085 DpmMockContext.CALLER_UID);
2086
2087 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2088 .setFactoryResetProtectionAccounts(new ArrayList<>())
2089 .setFactoryResetProtectionDisabled(true)
2090 .build();
2091 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2092
2093 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2094 assertThat(result).isEqualTo(policy);
2095 assertPoliciesAreEqual(policy, result);
2096
2097 verify(mContext.spiedContext).sendBroadcastAsUser(
2098 MockUtils.checkIntentAction(
2099 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2100 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2101 }
2102
2103 public void testSetFactoryResetProtectionPolicyFailWithPO() throws Exception {
2104 setupProfileOwner();
2105
2106 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2107 .setFactoryResetProtectionDisabled(true)
2108 .build();
2109
2110 assertExpectException(SecurityException.class, null,
2111 () -> dpm.setFactoryResetProtectionPolicy(admin1, policy));
2112 }
2113
2114 public void testSetFactoryResetProtectionPolicyWithPOOfOrganizationOwnedDevice()
2115 throws Exception {
2116 setupProfileOwner();
2117 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2118
2119 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2120 DpmMockContext.CALLER_UID);
2121
2122 List<String> accounts = new ArrayList<>();
2123 accounts.add("Account 1");
2124 accounts.add("Account 2");
2125
2126 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2127 .setFactoryResetProtectionAccounts(accounts)
2128 .build();
2129
2130 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2131
2132 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(admin1);
2133 assertThat(result).isEqualTo(policy);
2134 assertPoliciesAreEqual(policy, result);
2135
2136 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
2137 MockUtils.checkIntentAction(
2138 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
2139 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2140 verify(mContext.spiedContext).sendBroadcastAsUser(
2141 MockUtils.checkIntentAction(
2142 DevicePolicyManager.ACTION_PROFILE_OWNER_CHANGED),
2143 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2144 verify(mContext.spiedContext).sendBroadcastAsUser(
2145 MockUtils.checkIntentAction(
2146 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2147 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2148 }
2149
2150 public void testGetFactoryResetProtectionPolicyWithFrpManagementAgent()
2151 throws Exception {
2152 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2153 setupDeviceOwner();
2154 when(getServices().persistentDataBlockManagerInternal.getAllowedUid()).thenReturn(
2155 DpmMockContext.CALLER_UID);
2156
2157 FactoryResetProtectionPolicy policy = new FactoryResetProtectionPolicy.Builder()
2158 .setFactoryResetProtectionAccounts(new ArrayList<>())
2159 .setFactoryResetProtectionDisabled(true)
2160 .build();
2161
2162 dpm.setFactoryResetProtectionPolicy(admin1, policy);
2163
2164 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2165 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2166 dpm.setActiveAdmin(admin1, /*replace=*/ false);
2167 FactoryResetProtectionPolicy result = dpm.getFactoryResetProtectionPolicy(null);
2168 assertThat(result).isEqualTo(policy);
2169 assertPoliciesAreEqual(policy, result);
2170
2171 verify(mContext.spiedContext).sendBroadcastAsUser(
2172 MockUtils.checkIntentAction(
2173 DevicePolicyManager.ACTION_RESET_PROTECTION_POLICY_CHANGED),
2174 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
2175 }
2176
2177 private void assertPoliciesAreEqual(FactoryResetProtectionPolicy expectedPolicy,
2178 FactoryResetProtectionPolicy actualPolicy) {
2179 assertThat(actualPolicy.isFactoryResetProtectionDisabled()).isEqualTo(
2180 expectedPolicy.isFactoryResetProtectionDisabled());
2181 assertAccountsAreEqual(expectedPolicy.getFactoryResetProtectionAccounts(),
2182 actualPolicy.getFactoryResetProtectionAccounts());
2183 }
2184
2185 private void assertAccountsAreEqual(List<String> expectedAccounts,
2186 List<String> actualAccounts) {
2187 assertThat(actualAccounts).containsExactlyElementsIn(expectedAccounts);
2188 }
2189
Alex Johnstona552dd62020-01-17 17:05:25 +00002190 public void testSetApplicationHiddenWithDO() throws Exception {
2191 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2192 setupDeviceOwner();
2193 mContext.packageName = admin1.getPackageName();
2194 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2195
2196 String packageName = "com.google.android.test";
2197
2198 dpm.setApplicationHidden(admin1, packageName, true);
2199 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2200 true, UserHandle.USER_SYSTEM);
2201
2202 dpm.setApplicationHidden(admin1, packageName, false);
2203 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2204 false, UserHandle.USER_SYSTEM);
2205
2206 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2207 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
2208 verify(getServices().ipackageManager, never()).getPackageInfo(packageName,
2209 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2210 UserHandle.USER_SYSTEM);
2211 }
2212
2213 public void testSetApplicationHiddenWithPOOfOrganizationOwnedDevice() throws Exception {
2214 final int MANAGED_PROFILE_USER_ID = DpmMockContext.CALLER_USER_HANDLE;
2215 final int MANAGED_PROFILE_ADMIN_UID =
2216 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
2217 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
2218
2219 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2220 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2221 mContext.packageName = admin1.getPackageName();
2222 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
2223
2224 String packageName = "com.google.android.test";
2225
2226 PackageInfo packageInfo = new PackageInfo();
2227 packageInfo.applicationInfo = new ApplicationInfo();
2228 packageInfo.applicationInfo.flags = ApplicationInfo.FLAG_SYSTEM;
2229 when(getServices().userManager.getProfileParent(MANAGED_PROFILE_USER_ID))
2230 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
2231 when(getServices().ipackageManager.getPackageInfo(packageName,
2232 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM)).thenReturn(
2233 packageInfo);
2234 when(getServices().ipackageManager.getPackageInfo(packageName,
2235 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_SYSTEM_ONLY,
2236 UserHandle.USER_SYSTEM)).thenReturn(packageInfo);
2237
2238 parentDpm.setApplicationHidden(admin1, packageName, true);
2239 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2240 true, UserHandle.USER_SYSTEM);
2241
2242 parentDpm.setApplicationHidden(admin1, packageName, false);
2243 verify(getServices().ipackageManager).setApplicationHiddenSettingAsUser(packageName,
2244 false, UserHandle.USER_SYSTEM);
2245 }
2246
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002247 public void testGetMacAddress() throws Exception {
2248 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2249 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2250 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2251
2252 // In this test, change the caller user to "system".
2253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2254
2255 // Make sure admin1 is installed on system user.
2256 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2257
2258 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002259 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2260 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002261
2262 // DO needs to be an DA.
2263 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2264 assertTrue(dpm.isAdminActive(admin1));
2265
2266 // Test 2. Caller has DA, but not DO.
Eran Messeri6ba10db2019-12-04 15:53:27 +00002267 assertExpectException(SecurityException.class,
2268 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002269 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002270
2271 // Test 3. Caller has PO, but not DO.
2272 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Eran Messeri6ba10db2019-12-04 15:53:27 +00002273 assertExpectException(SecurityException.class,
2274 /* messageRegex= */ NOT_ORG_OWNED_PROFILE_OWNER_MSG,
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002275 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002276
2277 // Remove PO.
2278 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002279 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002280 // Test 4, Caller is DO now.
2281 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2282
xshu425b9a62018-12-13 14:18:18 -08002283 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002284 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002285
xshu425b9a62018-12-13 14:18:18 -08002286 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2287 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002288 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002289
2290 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002291 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2292 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002293 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002294 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002295
Eran Messeri6ba10db2019-12-04 15:53:27 +00002296 public void testGetMacAddressByOrgOwnedPO() throws Exception {
2297 setupProfileOwner();
2298 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
2299
2300 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2301 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
2302 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
2303 }
2304
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002305 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002306 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2307 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2308
2309 // In this test, change the caller user to "system".
2310 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2311
2312 // Make sure admin1 is installed on system user.
2313 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2314
2315 // Set admin1 as DA.
2316 dpm.setActiveAdmin(admin1, false);
2317 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002318 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2319 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002320
2321 // Set admin1 as PO.
2322 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002323 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2324 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002325
2326 // Remove PO and add DO.
2327 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002328 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002329 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2330
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002331 // admin1 is DO.
2332 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002333 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002334 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002335 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2336 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002337
2338 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002339 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002340 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002341 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2342 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002343
2344 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002345 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002346 dpm.reboot(admin1);
2347 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002348
2349 public void testSetGetSupportText() {
2350 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2351 dpm.setActiveAdmin(admin1, true);
2352 dpm.setActiveAdmin(admin2, true);
2353 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2354
2355 // Null default support messages.
2356 {
2357 assertNull(dpm.getLongSupportMessage(admin1));
2358 assertNull(dpm.getShortSupportMessage(admin1));
2359 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2360 assertNull(dpm.getShortSupportMessageForUser(admin1,
2361 DpmMockContext.CALLER_USER_HANDLE));
2362 assertNull(dpm.getLongSupportMessageForUser(admin1,
2363 DpmMockContext.CALLER_USER_HANDLE));
2364 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2365 }
2366
2367 // Only system can call the per user versions.
2368 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002369 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2370 () -> dpm.getShortSupportMessageForUser(admin1,
2371 DpmMockContext.CALLER_USER_HANDLE));
2372 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2373 () -> dpm.getLongSupportMessageForUser(admin1,
2374 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002375 }
2376
2377 // Can't set message for admin in another uid.
2378 {
2379 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002380 assertExpectException(SecurityException.class,
2381 /* messageRegex= */ "is not owned by uid",
2382 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002383 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2384 }
2385
2386 // Set/Get short returns what it sets and other admins text isn't changed.
2387 {
2388 final String supportText = "Some text to test with.";
2389 dpm.setShortSupportMessage(admin1, supportText);
2390 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2391 assertNull(dpm.getLongSupportMessage(admin1));
2392 assertNull(dpm.getShortSupportMessage(admin2));
2393
2394 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2395 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2396 DpmMockContext.CALLER_USER_HANDLE));
2397 assertNull(dpm.getShortSupportMessageForUser(admin2,
2398 DpmMockContext.CALLER_USER_HANDLE));
2399 assertNull(dpm.getLongSupportMessageForUser(admin1,
2400 DpmMockContext.CALLER_USER_HANDLE));
2401 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2402
2403 dpm.setShortSupportMessage(admin1, null);
2404 assertNull(dpm.getShortSupportMessage(admin1));
2405 }
2406
2407 // Set/Get long returns what it sets and other admins text isn't changed.
2408 {
2409 final String supportText = "Some text to test with.\nWith more text.";
2410 dpm.setLongSupportMessage(admin1, supportText);
2411 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2412 assertNull(dpm.getShortSupportMessage(admin1));
2413 assertNull(dpm.getLongSupportMessage(admin2));
2414
2415 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2416 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2417 DpmMockContext.CALLER_USER_HANDLE));
2418 assertNull(dpm.getLongSupportMessageForUser(admin2,
2419 DpmMockContext.CALLER_USER_HANDLE));
2420 assertNull(dpm.getShortSupportMessageForUser(admin1,
2421 DpmMockContext.CALLER_USER_HANDLE));
2422 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2423
2424 dpm.setLongSupportMessage(admin1, null);
2425 assertNull(dpm.getLongSupportMessage(admin1));
2426 }
2427 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002428
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002429 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002430 setAsProfileOwner(admin1);
2431
2432 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002433 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002434
2435 // Setup
2436 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2437 final String package1 = "com.example.one";
2438 final String package2 = "com.example.two";
2439 pkgsToRestrict.add(package1);
2440 pkgsToRestrict.add(package2);
2441 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2442 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002443 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002444
2445 // Verify
2446 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002447 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002448 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2449 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2450 eq(DpmMockContext.CALLER_USER_HANDLE));
2451
2452 // Setup
2453 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002454 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002455
2456 // Verify
2457 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002458 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002459 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2460 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2461 eq(DpmMockContext.CALLER_USER_HANDLE));
2462 }
2463
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002464 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002465 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2466 dpm.setActiveAdmin(admin1, true);
2467 assertTrue(dpm.isAdminActive(admin1));
2468 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2469
2470 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002471 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002472 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002473 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002474 }
2475
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002476 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002477 setAsProfileOwner(admin1);
2478
2479 // Setup
2480 final ArrayList<String> emptyList = new ArrayList<>();
2481 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2482 final String package1 = "com.example.one";
2483 final String package2 = "com.example.two";
2484 final String package3 = "com.example.three";
2485 pkgsToRestrict.add(package1);
2486 pkgsToRestrict.add(package2);
2487 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2488 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002489 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002490
2491 // Verify
2492 assertEquals(emptyList, excludedPkgs);
2493 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2494 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002495 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002496 DpmMockContext.CALLER_USER_HANDLE));
2497 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002498 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002499 DpmMockContext.CALLER_USER_HANDLE));
2500 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002501 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002502 DpmMockContext.CALLER_USER_HANDLE));
2503 }
2504
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002505 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002506 setAsProfileOwner(admin1);
2507 assertExpectException(SecurityException.class,
2508 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002509 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002510 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2511 dpm.clearProfileOwner(admin1);
2512
2513 setDeviceOwner();
2514 assertExpectException(SecurityException.class,
2515 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002516 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002517 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2518 clearDeviceOwner();
2519 }
2520
phweiss73145f42017-01-17 19:06:38 +01002521 public void testCreateAdminSupportIntent() throws Exception {
2522 // Setup device owner.
2523 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2524 setupDeviceOwner();
2525
2526 // Nonexisting permission returns null
2527 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2528 assertNull(intent);
2529
2530 // Existing permission that is not set returns null
2531 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2532 assertNull(intent);
2533
2534 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002535 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002536 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2537 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2538 .thenReturn(true);
2539 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2540 assertNull(intent);
2541
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002542 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2543 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2544 new UserManager.EnforcingUser(
2545 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2546 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002547 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002548 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002549 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2550 assertNotNull(intent);
2551 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2552 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2553 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002554 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002555 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2556 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2557
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002558 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2559 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002560
2561 // Camera is not disabled
2562 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2563 assertNull(intent);
2564
2565 // Camera is disabled
2566 dpm.setCameraDisabled(admin1, true);
2567 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2568 assertNotNull(intent);
2569 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2570 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2571
2572 // Screen capture is not disabled
2573 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2574 assertNull(intent);
2575
2576 // Screen capture is disabled
2577 dpm.setScreenCaptureDisabled(admin1, true);
2578 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2579 assertNotNull(intent);
2580 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2581 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2582
2583 // Same checks for different user
2584 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2585 // Camera should be disabled by device owner
2586 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2587 assertNotNull(intent);
2588 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2589 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2590 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2591 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2592 // ScreenCapture should not be disabled by device owner
2593 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2594 assertNull(intent);
2595 }
2596
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002597 /**
2598 * Test for:
2599 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002600 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002601 * {@link DevicePolicyManager#isAffiliatedUser}
2602 */
2603 public void testUserAffiliation() throws Exception {
2604 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2605 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2606 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2607
2608 // Check that the system user is unaffiliated.
2609 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2610 assertFalse(dpm.isAffiliatedUser());
2611
2612 // Set a device owner on the system user. Check that the system user becomes affiliated.
2613 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2614 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2615 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2616 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002617 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002618
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002619 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002620 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2621 setAsProfileOwner(admin2);
2622 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002623 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002624
2625 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2626 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002627 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002628 userAffiliationIds.add("red");
2629 userAffiliationIds.add("green");
2630 userAffiliationIds.add("blue");
2631 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002632 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002633 assertFalse(dpm.isAffiliatedUser());
2634
2635 // Have the device owner specify a set of affiliation ids that do not intersect with those
2636 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002637 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002638 deviceAffiliationIds.add("cyan");
2639 deviceAffiliationIds.add("yellow");
2640 deviceAffiliationIds.add("magenta");
2641 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2642 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002643 MoreAsserts.assertContentsInAnyOrder(
2644 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002645 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2646 assertFalse(dpm.isAffiliatedUser());
2647
2648 // Have the profile owner specify a set of affiliation ids that intersect with those
2649 // specified by the device owner. Check that the test user becomes affiliated.
2650 userAffiliationIds.add("yellow");
2651 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002652 MoreAsserts.assertContentsInAnyOrder(
2653 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002654 assertTrue(dpm.isAffiliatedUser());
2655
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002656 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002657 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002658 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002659 assertFalse(dpm.isAffiliatedUser());
2660
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002661 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2662 dpm.setAffiliationIds(admin2, userAffiliationIds);
2663 assertTrue(dpm.isAffiliatedUser());
2664 dpm.clearProfileOwner(admin2);
2665 assertFalse(dpm.isAffiliatedUser());
2666
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002667 // Check that the system user remains affiliated.
2668 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2669 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002670
2671 // Clear the device owner - the user becomes unaffiliated.
2672 clearDeviceOwner();
2673 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002674 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002675
2676 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002677 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002678 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2679 }
2680
2681 public void testSetUserProvisioningState_permission() throws Exception {
2682 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002683
2684 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2685 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2686 }
2687
2688 public void testSetUserProvisioningState_unprivileged() throws Exception {
2689 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002690 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2691 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2692 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002693 }
2694
2695 public void testSetUserProvisioningState_noManagement() {
2696 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002697 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002698 assertExpectException(IllegalStateException.class,
2699 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2700 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2701 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002702 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2703 }
2704
2705 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2706 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2707 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002708
2709 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2710 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2711 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2712 }
2713
2714 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2715 throws Exception {
2716 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2717 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002718
2719 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2720 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2721 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2722 }
2723
2724 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2725 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2726 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002727
2728 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2729 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2730 }
2731
2732 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2733 throws Exception {
2734 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002735
2736 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2737 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2738 DevicePolicyManager.STATE_USER_UNMANAGED);
2739 }
2740
2741 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2742 throws Exception {
2743 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002744
2745 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2746 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2747 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2748 }
2749
2750 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2751 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002752
2753 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2754 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2755 }
2756
2757 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2758 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002759
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002760 assertExpectException(IllegalStateException.class,
2761 /* messageRegex= */ "Cannot move to user provisioning state",
2762 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2763 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2764 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002765 }
2766
2767 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2768 throws Exception {
2769 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002770
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002771 assertExpectException(IllegalStateException.class,
2772 /* messageRegex= */ "Cannot move to user provisioning state",
2773 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2774 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2775 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002776 }
2777
2778 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002779 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2780 mContext.callerPermissions.add(permission.MANAGE_USERS);
2781
Alan Treadwayafad8782016-01-19 15:15:08 +00002782 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2783 for (int state : states) {
2784 dpm.setUserProvisioningState(state, userId);
2785 assertEquals(state, dpm.getUserProvisioningState());
2786 }
2787 }
2788
2789 private void setupProfileOwner() throws Exception {
2790 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2791
2792 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2793 dpm.setActiveAdmin(admin1, false);
2794 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2795
2796 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2797 }
2798
Alex Johnston8c503382019-11-19 11:12:15 +00002799 private void setupProfileOwnerOnUser0() throws Exception {
2800 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2801
2802 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2803 dpm.setActiveAdmin(admin1, false);
2804 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
2805
2806 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2807 }
2808
Alan Treadwayafad8782016-01-19 15:15:08 +00002809 private void setupDeviceOwner() throws Exception {
2810 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2811
2812 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2813 dpm.setActiveAdmin(admin1, false);
2814 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2815
2816 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2817 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002818
2819 public void testSetMaximumTimeToLock() {
2820 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2821
2822 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2823 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2824
Pavel Grafov75c0a892017-05-18 17:28:27 +01002825 reset(getServices().powerManagerInternal);
2826 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002827
2828 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002829 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2830 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002831 reset(getServices().powerManagerInternal);
2832 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002833
2834 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002835 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2836 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002837 reset(getServices().powerManagerInternal);
2838 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002839
2840 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002841 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2842 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002843 reset(getServices().powerManagerInternal);
2844 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002845
2846 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002847 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2848 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002849 reset(getServices().powerManagerInternal);
2850 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002851
2852 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002853 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2854 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002855 reset(getServices().powerManagerInternal);
2856 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002857
2858 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002859 reset(getServices().powerManagerInternal);
2860 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002861
Pavel Grafov28939982017-10-03 15:11:52 +01002862 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2863 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2864 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002865 reset(getServices().powerManagerInternal);
2866 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002867
2868 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002869 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2870 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002871 reset(getServices().powerManagerInternal);
2872 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002873
Pavel Grafov28939982017-10-03 15:11:52 +01002874 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002875 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002876 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2877 verifyStayOnWhilePluggedCleared(false);
2878 }
2879
Varun Shahb472b8f2019-09-23 23:01:06 -07002880 public void testIsActiveSupervisionApp() throws Exception {
2881 when(mServiceContext.resources
2882 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2883 .thenReturn(admin1.flattenToString());
2884
2885 final int PROFILE_USER = 15;
2886 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2887 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2888 mContext.binder.callingUid = PROFILE_ADMIN;
2889
2890 final DevicePolicyManagerInternal dpmi =
2891 LocalServices.getService(DevicePolicyManagerInternal.class);
2892 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2893 }
2894
Pavel Grafov28939982017-10-03 15:11:52 +01002895 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2896 // uses separate challenge.
2897 public void testSetMaximumTimeToLockProfile() throws Exception {
2898 final int PROFILE_USER = 15;
2899 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2900 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2901 mContext.binder.callingUid = PROFILE_ADMIN;
2902 final DevicePolicyManagerInternal dpmi =
2903 LocalServices.getService(DevicePolicyManagerInternal.class);
2904
2905 dpm.setMaximumTimeToLock(admin1, 0);
2906
2907 reset(getServices().powerManagerInternal);
2908 reset(getServices().settings);
2909
2910 // First add timeout for the profile.
2911 dpm.setMaximumTimeToLock(admin1, 10);
2912 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2913
2914 reset(getServices().powerManagerInternal);
2915 reset(getServices().settings);
2916
2917 // Add separate challenge
2918 when(getServices().lockPatternUtils
2919 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2920 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2921
2922 verifyScreenTimeoutCall(10L, PROFILE_USER);
2923 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2924
2925 reset(getServices().powerManagerInternal);
2926 reset(getServices().settings);
2927
2928 // Remove the timeout.
2929 dpm.setMaximumTimeToLock(admin1, 0);
2930 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2931 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2932
2933 reset(getServices().powerManagerInternal);
2934 reset(getServices().settings);
2935
2936 // Add it back.
2937 dpm.setMaximumTimeToLock(admin1, 10);
2938 verifyScreenTimeoutCall(10L, PROFILE_USER);
2939 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2940
2941 reset(getServices().powerManagerInternal);
2942 reset(getServices().settings);
2943
2944 // Remove separate challenge.
2945 reset(getServices().lockPatternUtils);
2946 when(getServices().lockPatternUtils
2947 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2948 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002949 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002950
2951 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2952 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2953
2954 reset(getServices().powerManagerInternal);
2955 reset(getServices().settings);
2956
2957 // Remove the timeout.
2958 dpm.setMaximumTimeToLock(admin1, 0);
2959 verifyScreenTimeoutCall(null, PROFILE_USER);
2960 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002961 }
2962
Michal Karpinski943aabd2016-10-06 11:09:25 +01002963 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2964 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2965 setupDeviceOwner();
2966 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2967
Michal Karpinskid084ca52017-01-18 15:54:18 +00002968 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2969 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2970 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2971 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2972 - ONE_MINUTE;
2973
2974 // verify that the minimum timeout cannot be modified on user builds (system property is
2975 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002976 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002977
2978 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2979 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2980 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2981
Pavel Grafov75c0a892017-05-18 17:28:27 +01002982 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002983
2984 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002985 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002986
Michal Karpinskid084ca52017-01-18 15:54:18 +00002987 // reset to default (0 means the admin is not participating, so default should be returned)
2988 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002989
2990 // aggregation should be the default if unset by any admin
2991 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2992 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2993
2994 // admin not participating by default
2995 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2996
2997 //clamping from the top
2998 dpm.setRequiredStrongAuthTimeout(admin1,
2999 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
3000 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
3001 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3002 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3003 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3004
Michal Karpinskid084ca52017-01-18 15:54:18 +00003005 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01003006 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3007 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3008 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3009 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3010
3011 // clamping from the bottom
3012 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
3013 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3014 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
3015
Michal Karpinskid084ca52017-01-18 15:54:18 +00003016 // values within range
3017 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
3018 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
3019 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
3020
3021 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
3022 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
3023 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01003024
3025 // reset to default
3026 dpm.setRequiredStrongAuthTimeout(admin1, 0);
3027 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
3028 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
3029 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
3030
3031 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003032 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
3033 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01003034 }
3035
Pavel Grafov28939982017-10-03 15:11:52 +01003036 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003037 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003038 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01003039 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003040 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003041 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01003042 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003043 }
Pavel Grafov28939982017-10-03 15:11:52 +01003044 }
3045
3046 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003047 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
3048 // UnfinishedVerificationException.
3049 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08003050
Esteban Talavera01576862016-12-15 11:16:44 +00003051 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003052 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00003053 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003054 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003055 .thenReturn(false);
3056 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003057 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3058 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003059 .thenReturn(true);
3060 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3061
3062 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003063 }
Victor Chang3e794af2016-03-04 13:48:17 +00003064
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003065 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
3066 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003067 mContext.packageName = admin1.getPackageName();
3068 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003069 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003070 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003071 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3072 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3073 false);
3074 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3075 }
3076
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003077 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
3078 setup_DeviceAdminFeatureOff();
3079 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3080 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3081 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Yanli Wan01c92552019-11-18 16:07:54 -08003082 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3083 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3085 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3086 assertCheckProvisioningPreCondition(
3087 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3088 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3089 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3090 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
3091 }
3092
Esteban Talavera01576862016-12-15 11:16:44 +00003093 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003094 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003095 .thenReturn(false);
3096 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003097 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3098 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003099 .thenReturn(true);
3100 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3101
3102 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003103 }
Victor Chang3e794af2016-03-04 13:48:17 +00003104
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003105 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
3106 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00003107 mContext.packageName = admin1.getPackageName();
3108 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003109 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003111 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3112 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3113 false);
3114 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3115
3116 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003117 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00003118 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003119 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003120 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3121 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3122 true);
3123 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
3124 }
3125
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003126 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
3127 setup_ManagedProfileFeatureOff();
3128 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3129 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3130 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003131 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3132 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003133 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3134 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3135 assertCheckProvisioningPreCondition(
3136 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3137 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3138 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3139 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3140
3141 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01003142 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003143 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3144 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003145 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3146 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003147 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3148 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3149 assertCheckProvisioningPreCondition(
3150 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3151 DevicePolicyManager.CODE_OK);
3152 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3153 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
3154 }
3155
Esteban Talavera01576862016-12-15 11:16:44 +00003156 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003157 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003158 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003159 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3160 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003161 .thenReturn(true);
3162 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3163
3164 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003165 }
Victor Chang3e794af2016-03-04 13:48:17 +00003166
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003167 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
3168 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003169 mContext.packageName = admin1.getPackageName();
3170 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003171 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003172 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003173 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3174 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3175 false /* because of non-split user */);
3176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3177 false /* because of non-split user */);
3178 }
3179
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003180 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003181 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003182 setup_nonSplitUser_firstBoot_primaryUser();
3183 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3184 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3185 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3187 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003188 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3189 DevicePolicyManager.CODE_OK);
3190 assertCheckProvisioningPreCondition(
3191 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3192 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3193 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3194 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3195 }
3196
Esteban Talavera01576862016-12-15 11:16:44 +00003197 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003198 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003199 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003200 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
3201 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003202 .thenReturn(true);
3203 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3204
3205 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 }
Victor Chang3e794af2016-03-04 13:48:17 +00003207
Nicolas Prevot45d29072017-01-18 16:11:19 +00003208 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
3209 setDeviceOwner();
3210 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3211 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3212 }
3213
3214 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3215 setup_nonSplitUser_withDo_primaryUser();
3216 final int MANAGED_PROFILE_USER_ID = 18;
3217 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003218 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003219 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003220 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003221 true)).thenReturn(true);
3222 }
3223
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003224 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3225 throws Exception {
3226 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003227 mContext.packageName = admin1.getPackageName();
3228 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003229 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3230 false/* because of completed device setup */);
Yanli Wan01c92552019-11-18 16:07:54 -08003231 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3232 false/* because of completed device setup */);
Victor Chang3e794af2016-03-04 13:48:17 +00003233 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3234 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3235 false/* because of non-split user */);
3236 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3237 false/* because of non-split user */);
3238 }
3239
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003240 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3241 throws Exception {
3242 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3243 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3244 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3245 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Yanli Wan01c92552019-11-18 16:07:54 -08003246 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3247 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003248 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3249 DevicePolicyManager.CODE_OK);
3250 assertCheckProvisioningPreCondition(
3251 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3252 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3253 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3254 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3255 }
3256
Nicolas Prevot45d29072017-01-18 16:11:19 +00003257 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3258 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003259 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003260 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3261
3262 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3263 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Yanli Wan01c92552019-11-18 16:07:54 -08003264 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3265 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003266 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Yanli Wan01c92552019-11-18 16:07:54 -08003267 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003268
Eran Messeri6ad0e192019-12-01 20:01:21 +00003269 // COMP mode NOT is allowed.
Esteban Talavera01576862016-12-15 11:16:44 +00003270 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003271 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3272 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003273
Eran Messeri6ad0e192019-12-01 20:01:21 +00003274 // And other DPCs can NOT provision a managed profile.
Esteban Talavera01576862016-12-15 11:16:44 +00003275 assertCheckProvisioningPreCondition(
3276 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003277 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003278 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003279 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3280 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3281 }
Esteban Talavera01576862016-12-15 11:16:44 +00003282
Nicolas Prevot45d29072017-01-18 16:11:19 +00003283 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3284 throws Exception {
3285 setup_nonSplitUser_withDo_primaryUser();
3286 mContext.packageName = admin1.getPackageName();
3287 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003288 // The DO should not be allowed to initiate provisioning if the restriction is set by
3289 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003290 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003291 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3292 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3293 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003294 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003295 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3296 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3297 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3298 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003299 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003300 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3301
3302 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003303 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003304 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003305 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003306 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3307 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3308 }
3309
Eran Messeri6ad0e192019-12-01 20:01:21 +00003310 public void testCheckCannotSetProfileOwnerWithDeviceOwner() throws Exception {
3311 setup_nonSplitUser_withDo_primaryUser();
3312 final int managedProfileUserId = 18;
3313 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 1308);
3314
3315 final int userId = UserHandle.getUserId(managedProfileAdminUid);
3316 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
3317 UserHandle.USER_SYSTEM);
3318 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
3319 setUpPackageManagerForFakeAdmin(admin1, managedProfileAdminUid, admin1);
3320 dpm.setActiveAdmin(admin1, false, userId);
3321 assertFalse(dpm.setProfileOwner(admin1, null, userId));
3322 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
3323 }
3324
3325 public void testCheckProvisioningPreCondition_nonSplitUser_attemptingComp() throws Exception {
Nicolas Prevot45d29072017-01-18 16:11:19 +00003326 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3327 mContext.packageName = admin1.getPackageName();
3328 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3329
3330 // We can delete the managed profile to create a new one, so provisioning is allowed.
3331 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003332 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3333 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003334 assertCheckProvisioningPreCondition(
3335 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3336 DpmMockContext.ANOTHER_PACKAGE_NAME,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003337 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3338 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003339 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3340 }
3341
3342 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3343 throws Exception {
3344 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3345 mContext.packageName = admin1.getPackageName();
3346 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003347 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003348 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3349 eq(UserHandle.SYSTEM)))
3350 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003351 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003352 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3353 eq(UserHandle.SYSTEM)))
3354 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003355
3356 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003357 assertCheckProvisioningPreCondition(
3358 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3359 DpmMockContext.ANOTHER_PACKAGE_NAME,
3360 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3361 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3362 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003363
3364 // But the device owner can still do it because it has set the restriction itself.
3365 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003366 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3367 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003368 }
3369
3370 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003371 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003372 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003373 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3374 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003375 .thenReturn(false);
3376 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3377
3378 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003379 }
Victor Chang3e794af2016-03-04 13:48:17 +00003380
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003381 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3382 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003383 mContext.packageName = admin1.getPackageName();
3384 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003385 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003386 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003387 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3388 false /* because canAddMoreManagedProfiles returns false */);
3389 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3390 true);
3391 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3392 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003393 }
3394
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003395 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3396 throws Exception {
3397 setup_splitUser_firstBoot_systemUser();
3398 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3399 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3400 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003401 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3402 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003403 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003404 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003405 assertCheckProvisioningPreCondition(
3406 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3407 DevicePolicyManager.CODE_OK);
3408 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3409 DevicePolicyManager.CODE_SYSTEM_USER);
3410 }
3411
Esteban Talavera01576862016-12-15 11:16:44 +00003412 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003413 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003414 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003415 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3416 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003417 .thenReturn(false);
3418 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3419
3420 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003421 }
Victor Chang3e794af2016-03-04 13:48:17 +00003422
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003423 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3424 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003425 mContext.packageName = admin1.getPackageName();
3426 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003427 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3428 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003429 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3430 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003431 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3432 false /* because canAddMoreManagedProfiles returns false */);
3433 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3434 true/* it's undefined behavior. Can be changed into false in the future */);
3435 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3436 false/* because calling uid is system user */);
3437 }
3438
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003439 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3440 throws Exception {
3441 setup_splitUser_afterDeviceSetup_systemUser();
3442 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3443 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3444 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003445 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3446 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003447 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003448 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003449 assertCheckProvisioningPreCondition(
3450 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3451 DevicePolicyManager.CODE_OK);
3452 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3453 DevicePolicyManager.CODE_SYSTEM_USER);
3454 }
3455
Esteban Talavera01576862016-12-15 11:16:44 +00003456 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003457 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003458 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003459 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3460 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003461 true)).thenReturn(true);
3462 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3463
3464 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003465 }
Victor Chang3e794af2016-03-04 13:48:17 +00003466
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003467 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3468 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003469 mContext.packageName = admin1.getPackageName();
3470 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003471 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
Yanli Wan01c92552019-11-18 16:07:54 -08003472 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003473 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3474 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3475 true);
3476 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003477 }
3478
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003479 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003480 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003481 setup_splitUser_firstBoot_primaryUser();
3482 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3483 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3484 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003485 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3486 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003487 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3488 DevicePolicyManager.CODE_OK);
3489 assertCheckProvisioningPreCondition(
3490 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3491 DevicePolicyManager.CODE_OK);
3492 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3493 DevicePolicyManager.CODE_OK);
3494 }
3495
Esteban Talavera01576862016-12-15 11:16:44 +00003496 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003497 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003498 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003499 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3500 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003501 true)).thenReturn(true);
3502 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3503
3504 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003505 }
Victor Chang3e794af2016-03-04 13:48:17 +00003506
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003507 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3508 throws Exception {
3509 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003510 mContext.packageName = admin1.getPackageName();
3511 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003512 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3513 true/* it's undefined behavior. Can be changed into false in the future */);
Yanli Wan01c92552019-11-18 16:07:54 -08003514 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3515 true/* it's undefined behavior. Can be changed into false in the future */);
Victor Chang3e794af2016-03-04 13:48:17 +00003516 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3517 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3518 true/* it's undefined behavior. Can be changed into false in the future */);
3519 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3520 false/* because user setup completed */);
3521 }
3522
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003523 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003524 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003525 setup_splitUser_afterDeviceSetup_primaryUser();
3526 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3527 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3528 DevicePolicyManager.CODE_OK);
Yanli Wan01c92552019-11-18 16:07:54 -08003529 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_FINANCED_DEVICE,
3530 DevicePolicyManager.CODE_OK);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003531 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3532 DevicePolicyManager.CODE_OK);
3533 assertCheckProvisioningPreCondition(
3534 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3535 DevicePolicyManager.CODE_OK);
3536 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3537 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3538 }
3539
Esteban Talavera01576862016-12-15 11:16:44 +00003540 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003541 setDeviceOwner();
3542
Pavel Grafov75c0a892017-05-18 17:28:27 +01003543 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003544 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003545 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3546 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003547 .thenReturn(false);
3548 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3549
3550 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003551 }
Victor Chang3e794af2016-03-04 13:48:17 +00003552
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003553 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3554 throws Exception {
3555 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003556 mContext.packageName = admin1.getPackageName();
3557 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003558 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3559 false /* can't provision managed profile on system user */);
3560 }
3561
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003562 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003563 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003564 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3565 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3566 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3567 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3568 }
3569
3570 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003571 setDeviceOwner();
3572
Pavel Grafov75c0a892017-05-18 17:28:27 +01003573 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003574 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003575 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Eran Messeri6ad0e192019-12-01 20:01:21 +00003576 when(getServices().userManager.getProfileParent(DpmMockContext.CALLER_USER_HANDLE))
3577 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
Pavel Grafov75c0a892017-05-18 17:28:27 +01003578 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003579 true)).thenReturn(true);
3580 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3581
3582 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003583 }
Victor Chang3e794af2016-03-04 13:48:17 +00003584
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003585 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3586 throws Exception {
3587 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003588 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3589 mContext.packageName = admin1.getPackageName();
Eran Messeri6ad0e192019-12-01 20:01:21 +00003590 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
Victor Chang3e794af2016-03-04 13:48:17 +00003591 }
3592
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003593 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003594 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003595 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3596 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003597
Eran Messeri6ad0e192019-12-01 20:01:21 +00003598 // COMP mode is NOT allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003599 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Eran Messeri6ad0e192019-12-01 20:01:21 +00003600 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003601 }
3602
3603 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003604 setDeviceOwner();
3605
Pavel Grafov75c0a892017-05-18 17:28:27 +01003606 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003607 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003608 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3609 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003610 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3611 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003612 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003613 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003614 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003615 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003616 true)).thenReturn(true);
3617 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3618
3619 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003620 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003621
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003622 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3623 throws Exception {
3624 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003625 mContext.packageName = admin1.getPackageName();
3626 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003627 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3628 }
3629
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003630 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3631 throws Exception {
3632 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3633 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3634 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3635 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3636 }
3637
3638 public void testCheckProvisioningPreCondition_permission() {
3639 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003640 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3641 () -> dpm.checkProvisioningPreCondition(
3642 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003643 }
3644
Victor Chang3577ed22016-08-25 18:49:26 +01003645 public void testForceUpdateUserSetupComplete_permission() {
3646 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003647 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3648 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003649 }
3650
3651 public void testForceUpdateUserSetupComplete_systemUser() {
3652 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3653 // GIVEN calling from user 20
3654 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003655 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3656 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003657 }
3658
3659 public void testForceUpdateUserSetupComplete_userbuild() {
3660 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3661 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3662
3663 final int userId = UserHandle.USER_SYSTEM;
3664 // GIVEN userComplete is false in SettingsProvider
3665 setUserSetupCompleteForUser(false, userId);
3666
3667 // GIVEN userComplete is true in DPM
3668 DevicePolicyManagerService.DevicePolicyData userData =
3669 new DevicePolicyManagerService.DevicePolicyData(userId);
3670 userData.mUserSetupComplete = true;
3671 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3672
3673 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003674 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003675
3676 assertTrue(dpms.hasUserSetupCompleted());
3677
3678 dpm.forceUpdateUserSetupComplete();
3679
3680 // THEN the state in dpms is not changed
3681 assertTrue(dpms.hasUserSetupCompleted());
3682 }
3683
3684 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3685 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3686 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3687
3688 final int userId = UserHandle.USER_SYSTEM;
3689 // GIVEN userComplete is false in SettingsProvider
3690 setUserSetupCompleteForUser(false, userId);
3691
3692 // GIVEN userComplete is true in DPM
3693 DevicePolicyManagerService.DevicePolicyData userData =
3694 new DevicePolicyManagerService.DevicePolicyData(userId);
3695 userData.mUserSetupComplete = true;
3696 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3697
3698 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003699 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003700
3701 assertTrue(dpms.hasUserSetupCompleted());
3702
3703 dpm.forceUpdateUserSetupComplete();
3704
3705 // THEN the state in dpms is not changed
3706 assertFalse(dpms.hasUserSetupCompleted());
3707 }
3708
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003709 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003710 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003711 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003712
3713 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3714 runAsCaller(mAdmin1Context, dpms, dpm -> {
3715 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3716 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003717 }
3718
3719 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3720 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3721 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003722
3723 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3724 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003725 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003726 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3727 .thenReturn(true);
3728
3729 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003730 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003731
3732 // Enabling logging should not change the timestamp.
3733 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003734 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003735 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003736 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003737 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003738 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003739
3740 // Retrieving the logs should update the timestamp.
3741 final long beforeRetrieval = System.currentTimeMillis();
3742 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003743 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003744 final long afterRetrieval = System.currentTimeMillis();
3745 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3746 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3747
3748 // Retrieving the pre-boot logs should update the timestamp.
3749 Thread.sleep(2);
3750 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003751 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003752 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3753
3754 // Checking the timestamp again should not change it.
3755 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003756 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003757
3758 // Retrieving the logs again should update the timestamp.
3759 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003760 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003761 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3762
3763 // Disabling logging should not change the timestamp.
3764 Thread.sleep(2);
3765 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003766 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003767
3768 // Restarting the DPMS should not lose the timestamp.
3769 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003770 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003771
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003772 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3773 mContext.binder.callingUid = 1234567;
3774 mContext.callerPermissions.add(permission.MANAGE_USERS);
3775 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3776 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3777
3778 // System can retrieve the timestamp.
3779 mContext.binder.clearCallingIdentity();
3780 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3781
3782 // Removing the device owner should clear the timestamp.
3783 clearDeviceOwner();
3784 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003785 }
3786
Alex Johnstonf13a6fb2020-01-15 11:11:23 +00003787 public void testSetLockdownAdminConfiguredNetworksWithDO() throws Exception {
3788 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3789 setupDeviceOwner();
3790 dpm.setLockdownAdminConfiguredNetworks(admin1, true);
3791 verify(getServices().settings).settingsGlobalPutInt(
3792 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3793
3794 dpm.setLockdownAdminConfiguredNetworks(admin1, false);
3795 verify(getServices().settings).settingsGlobalPutInt(
3796 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3797 }
3798
3799 public void testSetLockdownAdminConfiguredNetworksWithPO() throws Exception {
3800 setupProfileOwner();
3801 assertExpectException(SecurityException.class, null,
3802 () -> dpm.setLockdownAdminConfiguredNetworks(admin1, false));
3803 verify(getServices().settings, never()).settingsGlobalPutInt(
3804 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3805 }
3806
3807 public void testSetLockdownAdminConfiguredNetworksWithPOOfOrganizationOwnedDevice()
3808 throws Exception {
3809 setupProfileOwner();
3810 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3811 dpm.setLockdownAdminConfiguredNetworks(admin1, true);
3812 verify(getServices().settings).settingsGlobalPutInt(
3813 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 1);
3814
3815 dpm.setLockdownAdminConfiguredNetworks(admin1, false);
3816 verify(getServices().settings).settingsGlobalPutInt(
3817 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, 0);
3818 }
3819
yuemingw0de748d2017-11-15 19:22:27 +00003820 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3821 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3822 setupDeviceOwner();
3823 assertExpectException(SecurityException.class, null, () ->
3824 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3825 }
3826
yuemingwc0281f12018-03-28 15:58:49 +01003827 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003828 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3829 setupDeviceOwner();
3830 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003831 verify(getServices().settings).settingsSystemPutStringForUser(
3832 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3833 }
3834
3835 public void testSetSystemSettingWithPO() throws Exception {
3836 setupProfileOwner();
3837 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3838 verify(getServices().settings).settingsSystemPutStringForUser(
3839 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003840 }
3841
Alex Johnston8c503382019-11-19 11:12:15 +00003842 public void testSetAutoTimeModifiesSetting() throws Exception {
3843 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3844 setupDeviceOwner();
3845 dpm.setAutoTime(admin1, true);
3846 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3847
3848 dpm.setAutoTime(admin1, false);
3849 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3850 }
3851
3852 public void testSetAutoTimeWithPOOnUser0() throws Exception {
3853 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3854 setupProfileOwnerOnUser0();
3855 dpm.setAutoTime(admin1, true);
3856 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3857
3858 dpm.setAutoTime(admin1, false);
3859 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3860 }
3861
3862 public void testSetAutoTimeFailWithPONotOnUser0() throws Exception {
3863 setupProfileOwner();
3864 assertExpectException(SecurityException.class, null, () -> dpm.setAutoTime(admin1, false));
3865 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3866 }
3867
3868 public void testSetAutoTimeWithPOOfOrganizationOwnedDevice() throws Exception {
3869 setupProfileOwner();
3870 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3871
3872 dpm.setAutoTime(admin1, true);
3873 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 1);
3874
3875 dpm.setAutoTime(admin1, false);
3876 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME, 0);
3877 }
3878
Alex Johnstona44d7292019-12-12 15:34:35 +00003879 public void testSetAutoTimeZoneModifiesSetting() throws Exception {
3880 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3881 setupDeviceOwner();
3882 dpm.setAutoTimeZone(admin1, true);
3883 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3884
3885 dpm.setAutoTimeZone(admin1, false);
3886 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3887 }
3888
3889 public void testSetAutoTimeZoneWithPOOnUser0() throws Exception {
3890 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3891 setupProfileOwnerOnUser0();
3892 dpm.setAutoTimeZone(admin1, true);
3893 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3894
3895 dpm.setAutoTimeZone(admin1, false);
3896 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3897 }
3898
3899 public void testSetAutoTimeZoneFailWithPONotOnUser0() throws Exception {
3900 setupProfileOwner();
3901 assertExpectException(SecurityException.class, null,
3902 () -> dpm.setAutoTimeZone(admin1, false));
3903 verify(getServices().settings, never()).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE,
3904 0);
3905 }
3906
3907 public void testSetAutoTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
3908 setupProfileOwner();
3909 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3910
3911 dpm.setAutoTimeZone(admin1, true);
3912 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 1);
3913
3914 dpm.setAutoTimeZone(admin1, false);
3915 verify(getServices().settings).settingsGlobalPutInt(Settings.Global.AUTO_TIME_ZONE, 0);
3916 }
3917
Eran Messeria1015c82019-12-18 15:27:04 +00003918 public void testIsOrganizationOwnedDevice() throws Exception {
3919 setupProfileOwner();
3920 // Set up the user manager to return correct user info
3921 UserInfo managedProfileUserInfo = new UserInfo(DpmMockContext.CALLER_USER_HANDLE,
3922 "managed profile",
3923 UserInfo.FLAG_MANAGED_PROFILE);
3924 when(getServices().userManager.getUsers())
3925 .thenReturn(Arrays.asList(managedProfileUserInfo));
3926
Eran Messeri41c2aed2020-01-13 15:10:12 +00003927 // Any caller should be able to call this method.
Eran Messeria1015c82019-12-18 15:27:04 +00003928 assertFalse(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3929 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3930 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3931
3932 // A random caller from another user should also be able to get the right result.
3933 mContext.binder.callingUid = DpmMockContext.ANOTHER_UID;
3934 assertTrue(dpm.isOrganizationOwnedDeviceWithManagedProfile());
3935 }
3936
yuemingwe43cdf72017-10-12 16:52:11 +01003937 public void testSetTime() throws Exception {
3938 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3939 setupDeviceOwner();
3940 dpm.setTime(admin1, 0);
Neil Fullere3767562019-11-23 11:33:57 +00003941
3942 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3943 @Override
3944 public boolean matches(Object item) {
3945 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3946 return suggestion.getUtcTime().getValue() == 0;
3947 }
3948 @Override
3949 public void describeTo(Description description) {
3950 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3951 }
3952 };
3953 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
yuemingwe43cdf72017-10-12 16:52:11 +01003954 }
3955
3956 public void testSetTimeFailWithPO() throws Exception {
3957 setupProfileOwner();
3958 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3959 }
3960
Alex Johnstone81f05c2019-12-19 12:06:24 +00003961 public void testSetTimeWithPOOfOrganizationOwnedDevice() throws Exception {
3962 setupProfileOwner();
3963 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
3964 dpm.setTime(admin1, 0);
3965
3966 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3967 @Override
3968 public boolean matches(Object item) {
3969 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3970 return suggestion.getUtcTime().getValue() == 0;
3971 }
3972 @Override
3973 public void describeTo(Description description) {
3974 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3975 }
3976 };
3977 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
3978 }
3979
yuemingwe43cdf72017-10-12 16:52:11 +01003980 public void testSetTimeWithAutoTimeOn() throws Exception {
3981 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3982 setupDeviceOwner();
3983 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3984 .thenReturn(1);
3985 assertFalse(dpm.setTime(admin1, 0));
3986 }
3987
3988 public void testSetTimeZone() throws Exception {
3989 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3990 setupDeviceOwner();
3991 dpm.setTimeZone(admin1, "Asia/Shanghai");
Neil Fuller106f18a2019-12-04 13:27:04 +00003992 ManualTimeZoneSuggestion suggestion =
3993 TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
3994 verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
yuemingwe43cdf72017-10-12 16:52:11 +01003995 }
3996
3997 public void testSetTimeZoneFailWithPO() throws Exception {
3998 setupProfileOwner();
3999 assertExpectException(SecurityException.class, null,
4000 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
4001 }
4002
Alex Johnstone81f05c2019-12-19 12:06:24 +00004003 public void testSetTimeZoneWithPOOfOrganizationOwnedDevice() throws Exception {
4004 setupProfileOwner();
4005 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
4006 dpm.setTimeZone(admin1, "Asia/Shanghai");
4007 ManualTimeZoneSuggestion suggestion =
4008 TimeZoneDetector.createManualTimeZoneSuggestion("Asia/Shanghai", "Test debug info");
4009 verify(getServices().timeZoneDetector).suggestManualTimeZone(suggestion);
4010 }
4011
yuemingwe43cdf72017-10-12 16:52:11 +01004012 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
4013 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4014 setupDeviceOwner();
4015 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
4016 .thenReturn(1);
4017 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
4018 }
4019
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004020 public void testGetLastBugReportRequestTime() throws Exception {
4021 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4022 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004023
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004024 mContext.packageName = admin1.getPackageName();
4025 mContext.applicationInfo = new ApplicationInfo();
4026 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4027 .thenReturn(Color.WHITE);
4028 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4029 anyObject())).thenReturn(Color.WHITE);
4030
Esteban Talaverad36dd152016-12-15 08:51:45 +00004031 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4032 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004033 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00004034
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004035 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004036 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004037
4038 // Requesting a bug report should update the timestamp.
4039 final long beforeRequest = System.currentTimeMillis();
4040 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004041 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004042 final long afterRequest = System.currentTimeMillis();
4043 assertTrue(bugReportRequestTime >= beforeRequest);
4044 assertTrue(bugReportRequestTime <= afterRequest);
4045
4046 // Checking the timestamp again should not change it.
4047 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004048 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004049
4050 // Restarting the DPMS should not lose the timestamp.
4051 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004052 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004053
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004054 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4055 mContext.binder.callingUid = 1234567;
4056 mContext.callerPermissions.add(permission.MANAGE_USERS);
4057 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4058 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4059
4060 // System can retrieve the timestamp.
4061 mContext.binder.clearCallingIdentity();
4062 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
4063
4064 // Removing the device owner should clear the timestamp.
4065 clearDeviceOwner();
4066 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004067 }
4068
4069 public void testGetLastNetworkLogRetrievalTime() throws Exception {
4070 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4071 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00004072 mContext.packageName = admin1.getPackageName();
4073 mContext.applicationInfo = new ApplicationInfo();
4074 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
4075 .thenReturn(Color.WHITE);
4076 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
4077 anyObject())).thenReturn(Color.WHITE);
4078
4079 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
4080 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01004082 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004083 .thenReturn(true);
4084
4085 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004086 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004087
4088 // Attempting to retrieve logs without enabling logging should not change the timestamp.
4089 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004090 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004091
4092 // Enabling logging should not change the timestamp.
4093 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004094 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004095
4096 // Retrieving the logs should update the timestamp.
4097 final long beforeRetrieval = System.currentTimeMillis();
4098 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004099 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004100 final long afterRetrieval = System.currentTimeMillis();
4101 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
4102 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
4103
4104 // Checking the timestamp again should not change it.
4105 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004106 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004107
4108 // Retrieving the logs again should update the timestamp.
4109 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004110 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004111 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
4112
4113 // Disabling logging should not change the timestamp.
4114 Thread.sleep(2);
4115 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004116 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004117
4118 // Restarting the DPMS should not lose the timestamp.
4119 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01004120 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4121
4122 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
4123 mContext.binder.callingUid = 1234567;
4124 mContext.callerPermissions.add(permission.MANAGE_USERS);
4125 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4126 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4127
4128 // System can retrieve the timestamp.
4129 mContext.binder.clearCallingIdentity();
4130 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
4131
4132 // Removing the device owner should clear the timestamp.
4133 clearDeviceOwner();
4134 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01004135 }
4136
Tony Mak2f26b792016-11-28 17:54:51 +00004137 public void testGetBindDeviceAdminTargetUsers() throws Exception {
4138 // Setup device owner.
4139 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4140 setupDeviceOwner();
4141
4142 // Only device owner is setup, the result list should be empty.
4143 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4144 MoreAsserts.assertEmpty(targetUsers);
4145
Tony Mak2f26b792016-11-28 17:54:51 +00004146 // Add a secondary user, it should never talk with.
4147 final int ANOTHER_USER_ID = 36;
Alex Johnston755e3772019-11-29 03:27:22 +00004148 getServices().addUser(ANOTHER_USER_ID, 0, UserManager.USER_TYPE_FULL_SECONDARY);
Tony Mak2f26b792016-11-28 17:54:51 +00004149
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004150 // Since the managed profile is not affiliated, they should not be allowed to talk to each
4151 // other.
4152 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4153 MoreAsserts.assertEmpty(targetUsers);
4154
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004155 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01004156 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004157 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4158 dpm.setAffiliationIds(admin1, userAffiliationIds);
4159
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004160 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01004161 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00004162
4163 // Since the managed profile is not affiliated any more, they should not be allowed to talk
4164 // to each other.
4165 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4166 MoreAsserts.assertEmpty(targetUsers);
4167
4168 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4169 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
4170 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00004171 }
4172
Jason Parks3c13b642017-11-28 15:39:43 -06004173 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01004174 verifyLockTaskState(userId, new String[0],
4175 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06004176 }
4177
4178 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
4179 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07004180 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06004181 }
4182
4183 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
4184 int flags) throws Exception {
4185 mContext.binder.callingUid = uid;
4186 dpm.setLockTaskPackages(who, packages);
4187 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
4188 for (String p : packages) {
4189 assertTrue(dpm.isLockTaskPermitted(p));
4190 }
4191 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
4192 // Test to see if set lock task features can be set
4193 dpm.setLockTaskFeatures(who, flags);
4194 verifyLockTaskState(userId, packages, flags);
4195 }
4196
4197 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
4198 int flags) throws Exception {
4199 mContext.binder.callingUid = uid;
4200 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4201 () -> dpm.setLockTaskPackages(who, packages));
4202 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4203 () -> dpm.getLockTaskPackages(who));
4204 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
4205 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
4206 () -> dpm.setLockTaskFeatures(who, flags));
4207 }
4208
Jason Parks3c13b642017-11-28 15:39:43 -06004209 public void testLockTaskPolicyForProfileOwner() throws Exception {
4210 // Setup a PO
4211 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4212 setAsProfileOwner(admin1);
4213 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
4214
4215 final String[] poPackages = {"poPackage1", "poPackage2"};
4216 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004217 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4218 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004219 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
4220 poPackages, poFlags);
4221
4222 // Set up a managed profile managed by different package (package name shouldn't matter)
4223 final int MANAGED_PROFILE_USER_ID = 15;
4224 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
4225 final ComponentName adminDifferentPackage =
4226 new ComponentName("another.package", "whatever.class");
4227 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
4228 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
4229
4230 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
4231 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4232 final String[] mpoPackages = {"poPackage1", "poPackage2"};
4233 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00004234 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
4235 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06004236 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00004237 }
4238
Benjamin Franzcaffa772018-02-05 16:36:10 +00004239 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
4240 // Setup a device owner.
4241 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4242 setupDeviceOwner();
4243 // Lock task policy is updated when loading user data.
4244 verifyLockTaskState(UserHandle.USER_SYSTEM);
4245
4246 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
4247 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
4248 assertExpectException(IllegalArgumentException.class,
4249 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4250 () -> dpm.setLockTaskFeatures(admin1, flags));
4251 }
4252
Yvonne Jiangb7024a22019-12-05 16:57:08 -08004253 public void testSecondaryLockscreen_profileOwner() throws Exception {
4254 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4255
4256 // Initial state is disabled.
4257 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4258
4259 // Profile owner can set enabled state.
4260 setAsProfileOwner(admin1);
4261 dpm.setSecondaryLockscreenEnabled(admin1, true);
4262 assertTrue(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4263
4264 // Managed profile managed by different package is unaffiliated - cannot set enabled.
4265 final int managedProfileUserId = 15;
4266 final int managedProfileAdminUid = UserHandle.getUid(managedProfileUserId, 20456);
4267 final ComponentName adminDifferentPackage =
4268 new ComponentName("another.package", "whatever.class");
4269 addManagedProfile(adminDifferentPackage, managedProfileAdminUid, admin2);
4270 mContext.binder.callingUid = managedProfileAdminUid;
4271 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4272 () -> dpm.setSecondaryLockscreenEnabled(adminDifferentPackage, false));
4273 }
4274
4275 public void testSecondaryLockscreen_deviceOwner() throws Exception {
4276 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4277
4278 // Initial state is disabled.
4279 assertFalse(dpm.isSecondaryLockscreenEnabled(UserHandle.USER_SYSTEM));
4280
4281 // Device owners can set enabled state.
4282 setupDeviceOwner();
4283 dpm.setSecondaryLockscreenEnabled(admin1, true);
4284 assertTrue(dpm.isSecondaryLockscreenEnabled(UserHandle.USER_SYSTEM));
4285 }
4286
4287 public void testSecondaryLockscreen_nonOwner() throws Exception {
4288 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4289
4290 // Initial state is disabled.
4291 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4292
4293 // Non-DO/PO cannot set enabled state.
4294 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4295 () -> dpm.setSecondaryLockscreenEnabled(admin1, true));
4296 assertFalse(dpm.isSecondaryLockscreenEnabled(DpmMockContext.CALLER_USER_HANDLE));
4297 }
4298
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01004299 public void testIsDeviceManaged() throws Exception {
4300 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4301 setupDeviceOwner();
4302
4303 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
4304 // find out that the device has a device owner.
4305 assertTrue(dpm.isDeviceManaged());
4306 mContext.binder.callingUid = 1234567;
4307 mContext.callerPermissions.add(permission.MANAGE_USERS);
4308 assertTrue(dpm.isDeviceManaged());
4309 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4310 mContext.binder.clearCallingIdentity();
4311 assertTrue(dpm.isDeviceManaged());
4312
4313 clearDeviceOwner();
4314
4315 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4316 // not have a device owner.
4317 mContext.binder.callingUid = 1234567;
4318 mContext.callerPermissions.add(permission.MANAGE_USERS);
4319 assertFalse(dpm.isDeviceManaged());
4320 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4321 mContext.binder.clearCallingIdentity();
4322 assertFalse(dpm.isDeviceManaged());
4323 }
4324
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004325 public void testDeviceOwnerOrganizationName() throws Exception {
4326 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4327 setupDeviceOwner();
4328
4329 dpm.setOrganizationName(admin1, "organization");
4330
4331 // Device owner can retrieve organization managing the device.
4332 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4333
4334 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4335 mContext.binder.callingUid = 1234567;
4336 mContext.callerPermissions.add(permission.MANAGE_USERS);
4337 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4338 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4339
4340 // System can retrieve organization managing the device.
4341 mContext.binder.clearCallingIdentity();
4342 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4343
4344 // Removing the device owner clears the organization managing the device.
4345 clearDeviceOwner();
4346 assertNull(dpm.getDeviceOwnerOrganizationName());
4347 }
4348
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004349 public void testWipeDataManagedProfile() throws Exception {
4350 final int MANAGED_PROFILE_USER_ID = 15;
4351 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4352 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4353 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4354
4355 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004356 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004357 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004358 // Get mock reason string since we throw an IAE with empty string input.
4359 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4360 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004361
4362 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004363 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004364 MANAGED_PROFILE_USER_ID);
4365 }
4366
4367 public void testWipeDataManagedProfileDisallowed() throws Exception {
4368 final int MANAGED_PROFILE_USER_ID = 15;
4369 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4370 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4371
4372 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004373 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004374 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4375
Pavel Grafov75c0a892017-05-18 17:28:27 +01004376 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004377 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4378 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4379 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004380 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4381 thenReturn("Just a test string.");
4382
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004383 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004384 // The PO is not allowed to remove the profile if the user restriction was set on the
4385 // profile by the system
4386 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4387 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004388 }
4389
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004390 public void testWipeDataDeviceOwner() throws Exception {
4391 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004392 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004393 UserManager.DISALLOW_FACTORY_RESET,
4394 UserHandle.SYSTEM))
4395 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004396 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4397 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004398
4399 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004400 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004401 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4402 /*wipeEuicc=*/ eq(false));
4403 }
4404
4405 public void testWipeEuiccDataEnabled() throws Exception {
4406 setDeviceOwner();
4407 when(getServices().userManager.getUserRestrictionSource(
4408 UserManager.DISALLOW_FACTORY_RESET,
4409 UserHandle.SYSTEM))
4410 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004411 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4412 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004413
4414 dpm.wipeData(WIPE_EUICC);
4415 verify(getServices().recoverySystem).rebootWipeUserData(
4416 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4417 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004418 }
4419
4420 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4421 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004422 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004423 UserManager.DISALLOW_FACTORY_RESET,
4424 UserHandle.SYSTEM))
4425 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004426 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4427 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004428 // The DO is not allowed to wipe the device if the user restriction was set
4429 // by the system
4430 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4431 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004432 }
4433
4434 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4435 final int MANAGED_PROFILE_USER_ID = 15;
4436 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4437 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4438
4439 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004440 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004441 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4442
Pavel Grafov75c0a892017-05-18 17:28:27 +01004443 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004444 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4445 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4446 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4447
4448 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4449 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4450
4451 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4452 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4453 // Failed password attempts on the parent user are taken into account, as there isn't a
4454 // separate work challenge.
4455 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4456 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4457 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4458
4459 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4460 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004462 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004463 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004464 }
4465
4466 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4467 throws Exception {
4468 final int MANAGED_PROFILE_USER_ID = 15;
4469 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4470 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4471
4472 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004473 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004474 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4475
Pavel Grafov75c0a892017-05-18 17:28:27 +01004476 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004477 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4478 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4479 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4480
4481 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4482 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4483
4484 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4485 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4486 // Failed password attempts on the parent user are taken into account, as there isn't a
4487 // separate work challenge.
4488 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4489 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4490 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4491
4492 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4493 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004494 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004495 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004496 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004497 }
4498
4499 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4500 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004501 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004502 UserManager.DISALLOW_FACTORY_RESET,
4503 UserHandle.SYSTEM))
4504 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4505
4506 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4507
4508 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4509 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4510 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4511 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4512 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4513
4514 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4515 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004516 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004517 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4518 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004519 }
4520
4521 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4522 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004523 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004524 UserManager.DISALLOW_FACTORY_RESET,
4525 UserHandle.SYSTEM))
4526 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4527
4528 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4529
4530 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4531 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4532 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4533 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4534 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4535
4536 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004537 verifyZeroInteractions(getServices().recoverySystem);
4538 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004539 .removeUserEvenWhenDisallowed(anyInt());
4540 }
4541
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004542 public void testGetPermissionGrantState() throws Exception {
4543 final String permission = "some.permission";
4544 final String app1 = "com.example.app1";
4545 final String app2 = "com.example.app2";
4546
Pavel Grafov75c0a892017-05-18 17:28:27 +01004547 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004548 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004549 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004550 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004551 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004552 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4553 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004554 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004555 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004556 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004557 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004558 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004559 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4560
4561 // System can retrieve permission grant state.
4562 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004563 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004564 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4565 dpm.getPermissionGrantState(null, app1, permission));
4566 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4567 dpm.getPermissionGrantState(null, app2, permission));
4568
4569 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004570 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4571 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004572 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4573 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004574
4575 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004576 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4577 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004578 setAsProfileOwner(admin1);
4579 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4580 dpm.getPermissionGrantState(admin1, app1, permission));
4581 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4582 dpm.getPermissionGrantState(admin1, app2, permission));
4583 }
4584
Rubin Xuaab7a412016-12-30 21:13:29 +00004585 public void testResetPasswordWithToken() throws Exception {
4586 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4587 setupDeviceOwner();
4588 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004589 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4590 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4591
Rubin Xuaab7a412016-12-30 21:13:29 +00004592 // test adding a token
4593 final byte[] token = new byte[32];
4594 final long handle = 123456;
4595 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004596 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4597 nullable(EscrowTokenStateChangeCallback.class)))
4598 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004599 assertTrue(dpm.setResetPasswordToken(admin1, token));
4600
4601 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004602 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004603 .thenReturn(true);
4604 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4605
4606 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004607 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4608 eq(LockscreenCredential.createPassword(password)),
4609 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004610 eq(UserHandle.USER_SYSTEM)))
4611 .thenReturn(true);
4612 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4613
4614 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004615 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004616 .thenReturn(true);
4617 assertTrue(dpm.clearResetPasswordToken(admin1));
4618 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004619
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004620 public void testIsActivePasswordSufficient() throws Exception {
4621 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4622 mContext.packageName = admin1.getPackageName();
4623 setupDeviceOwner();
4624
4625 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4626 dpm.setPasswordMinimumLength(admin1, 8);
4627 dpm.setPasswordMinimumLetters(admin1, 6);
4628 dpm.setPasswordMinimumLowerCase(admin1, 3);
4629 dpm.setPasswordMinimumUpperCase(admin1, 1);
4630 dpm.setPasswordMinimumNonLetter(admin1, 1);
4631 dpm.setPasswordMinimumNumeric(admin1, 1);
4632 dpm.setPasswordMinimumSymbols(admin1, 0);
4633
Rubin Xucc391c22018-01-02 20:37:35 +00004634 reset(mContext.spiedContext);
4635
Pavel Grafov6f334842019-08-06 14:37:06 +01004636 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004637
4638 setActivePasswordState(passwordMetricsNoSymbols);
4639 assertTrue(dpm.isActivePasswordSufficient());
4640
4641 initializeDpms();
4642 reset(mContext.spiedContext);
4643 assertTrue(dpm.isActivePasswordSufficient());
4644
4645 // This call simulates the user entering the password for the first time after a reboot.
4646 // This causes password metrics to be reloaded into memory. Until this happens,
4647 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4648 // even if the DPC changes password requirements so that the password no longer meets the
4649 // requirements. This is a known limitation of the current implementation of
4650 // isActivePasswordSufficient() - see b/34218769.
4651 setActivePasswordState(passwordMetricsNoSymbols);
4652 assertTrue(dpm.isActivePasswordSufficient());
4653
4654 dpm.setPasswordMinimumSymbols(admin1, 1);
4655 // This assertion would fail if we had not called setActivePasswordState() again after
4656 // initializeDpms() - see previous comment.
4657 assertFalse(dpm.isActivePasswordSufficient());
4658
4659 initializeDpms();
4660 reset(mContext.spiedContext);
4661 assertFalse(dpm.isActivePasswordSufficient());
4662
Pavel Grafov6f334842019-08-06 14:37:06 +01004663 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004664
4665 setActivePasswordState(passwordMetricsWithSymbols);
4666 assertTrue(dpm.isActivePasswordSufficient());
4667 }
4668
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004669 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4670 // If there is no lock screen, the password is considered empty no matter what, because
4671 // it provides no security.
4672 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4673
4674 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4675 mContext.packageName = admin1.getPackageName();
4676 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004677 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4678 // When there is no lockscreen, user password metrics is always empty.
4679 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004680 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004681
4682 // If no password requirements are set, isActivePasswordSufficient should succeed.
4683 assertTrue(dpm.isActivePasswordSufficient());
4684
4685 // Now set some password quality requirements.
4686 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4687
4688 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004689 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004690 dpm.reportPasswordChanged(userHandle);
4691
4692 // No broadcast should be sent.
4693 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4694 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4695 MockUtils.checkUserHandle(userHandle));
4696
4697 // The active (nonexistent) password doesn't comply with the requirements.
4698 assertFalse(dpm.isActivePasswordSufficient());
4699 }
4700
Pavel Grafov75c0a892017-05-18 17:28:27 +01004701 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4702 throws Exception {
4703 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004704 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004705
Rubin Xu19854862019-08-15 16:37:23 +01004706 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4707 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004708 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004709
Rubin Xucc391c22018-01-02 20:37:35 +00004710 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4711 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004712 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004713 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4714 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004715 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004716 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4717 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004718 // userId, if the password checkpoint value changes.
4719 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4720 MockUtils.checkIntentAction(
4721 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4722 MockUtils.checkUserHandle(userHandle));
4723 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004724 MockUtils.checkIntentAction(
4725 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4726 MockUtils.checkUserHandle(userHandle));
4727
Pavel Grafov75c0a892017-05-18 17:28:27 +01004728 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4729 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004730 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004731
4732 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4733 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004734 MockUtils.checkUserHandle(userHandle),
4735 eq(null),
4736 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004737
4738 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4739 // let it finish with system uid, otherwise it will throw and crash.
4740 flushTasks();
4741
4742 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004743 }
4744
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004745 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4746 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4747 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4748 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4749 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4750 DpmMockContext.SYSTEM_UID);
4751 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4752 DpmMockContext.SYSTEM_UID);
4753
4754 // Set up a device owner.
4755 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004756 setupDeviceOwner();
4757
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004758 // First and second user set IMEs manually.
4759 mContext.binder.callingUid = firstUserSystemUid;
4760 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4761 mContext.binder.callingUid = secondUserSystemUid;
4762 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004763
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004764 // Device owner changes IME for first user.
4765 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004766 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004767 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004768 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004769 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004770 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004771 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004772 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4773 mContext.binder.callingUid = firstUserSystemUid;
4774 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4775 mContext.binder.callingUid = secondUserSystemUid;
4776 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004777
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004778 // Second user changes IME manually.
4779 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4780 mContext.binder.callingUid = firstUserSystemUid;
4781 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4782 mContext.binder.callingUid = secondUserSystemUid;
4783 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004784
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004785 // First user changes IME manually.
4786 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4787 mContext.binder.callingUid = firstUserSystemUid;
4788 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4789 mContext.binder.callingUid = secondUserSystemUid;
4790 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004791
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004792 // Device owner changes IME for first user again.
4793 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004794 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004795 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004796 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004797 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004798 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004799 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4800 mContext.binder.callingUid = firstUserSystemUid;
4801 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4802 mContext.binder.callingUid = secondUserSystemUid;
4803 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004804
4805 // Restarting the DPMS should not lose information.
4806 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004807 mContext.binder.callingUid = firstUserSystemUid;
4808 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4809 mContext.binder.callingUid = secondUserSystemUid;
4810 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004811
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004812 // Device owner can find out whether it set the current IME itself.
4813 mContext.binder.callingUid = deviceOwnerUid;
4814 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004815
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004816 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004817 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004818 mContext.binder.callingUid = firstUserSystemUid;
4819 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4820 mContext.binder.callingUid = secondUserSystemUid;
4821 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004822 }
4823
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004824 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4825 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4826 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4827 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4828 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4829 DpmMockContext.SYSTEM_UID);
4830 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4831 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004832
4833 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004834 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004835 setupProfileOwner();
4836
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004837 // First and second user set IMEs manually.
4838 mContext.binder.callingUid = firstUserSystemUid;
4839 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4840 mContext.binder.callingUid = secondUserSystemUid;
4841 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004842
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004843 // Profile owner changes IME for second user.
4844 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004845 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004846 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004847 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004848 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004849 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004850 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004851 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4852 mContext.binder.callingUid = firstUserSystemUid;
4853 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4854 mContext.binder.callingUid = secondUserSystemUid;
4855 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004856
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004857 // First user changes IME manually.
4858 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4859 mContext.binder.callingUid = firstUserSystemUid;
4860 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4861 mContext.binder.callingUid = secondUserSystemUid;
4862 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004863
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004864 // Second user changes IME manually.
4865 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4866 mContext.binder.callingUid = firstUserSystemUid;
4867 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4868 mContext.binder.callingUid = secondUserSystemUid;
4869 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004870
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004871 // Profile owner changes IME for second user again.
4872 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004873 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004874 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004875 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004876 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004877 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004878 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4879 mContext.binder.callingUid = firstUserSystemUid;
4880 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4881 mContext.binder.callingUid = secondUserSystemUid;
4882 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004883
4884 // Restarting the DPMS should not lose information.
4885 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004886 mContext.binder.callingUid = firstUserSystemUid;
4887 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4888 mContext.binder.callingUid = secondUserSystemUid;
4889 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004890
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004891 // Profile owner can find out whether it set the current IME itself.
4892 mContext.binder.callingUid = profileOwnerUid;
4893 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004894
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004895 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004896 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004897 mContext.binder.callingUid = firstUserSystemUid;
4898 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4899 mContext.binder.callingUid = secondUserSystemUid;
4900 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004901 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004902
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004903 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4904 throws Exception {
4905 // Set up a device owner.
4906 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4907 setupDeviceOwner();
4908 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4909 }
4910
4911 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4912 throws Exception {
4913 // Set up a profile owner.
4914 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4915 setupProfileOwner();
4916 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4917 }
4918
4919 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4920 int adminUid) throws Exception {
4921 mContext.binder.callingUid = adminUid;
4922 final int userId = UserHandle.getUserId(adminUid);
4923
4924 final String packageName = "some.package";
4925 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4926 admin1, Collections.singletonList(packageName)));
4927 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4928
4929 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4930 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4931
4932 // Attempt to set to empty list (which means no listener is whitelisted)
4933 mContext.binder.callingUid = adminUid;
4934 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004935 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004936 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4937
4938 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4939 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4940 }
4941
4942 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4943 // Set up a managed profile
4944 final int MANAGED_PROFILE_USER_ID = 15;
4945 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4946 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4947 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4948
4949 final String permittedListener = "some.package";
4950 setupPackageInPackageManager(
4951 permittedListener,
4952 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4953 /*appId=*/ 12345, /*flags=*/ 0);
4954
4955 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4956 admin1, Collections.singletonList(permittedListener)));
4957
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004958 // isNotificationListenerServicePermitted should throw if not called from System.
4959 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4960 () -> dpms.isNotificationListenerServicePermitted(
4961 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004962
4963 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4964 assertTrue(dpms.isNotificationListenerServicePermitted(
4965 permittedListener, MANAGED_PROFILE_USER_ID));
4966 }
4967
4968 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4969 throws Exception {
4970 // Set up a managed profile
4971 final int MANAGED_PROFILE_USER_ID = 15;
4972 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4973 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4974 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4975
4976 final String permittedListener = "permitted.package";
4977 int appId = 12345;
4978 setupPackageInPackageManager(
4979 permittedListener,
4980 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4981 appId, /*flags=*/ 0);
4982
4983 final String notPermittedListener = "not.permitted.package";
4984 setupPackageInPackageManager(
4985 notPermittedListener,
4986 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4987 ++appId, /*flags=*/ 0);
4988
4989 final String systemListener = "system.package";
4990 setupPackageInPackageManager(
4991 systemListener,
4992 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4993 ++appId, ApplicationInfo.FLAG_SYSTEM);
4994
4995 // By default all packages are allowed
4996 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4997
4998 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4999 assertTrue(dpms.isNotificationListenerServicePermitted(
5000 permittedListener, MANAGED_PROFILE_USER_ID));
5001 assertTrue(dpms.isNotificationListenerServicePermitted(
5002 notPermittedListener, MANAGED_PROFILE_USER_ID));
5003 assertTrue(dpms.isNotificationListenerServicePermitted(
5004 systemListener, MANAGED_PROFILE_USER_ID));
5005
5006 // Setting only one package in the whitelist
5007 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5008 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
5009 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005010 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005011 dpms.getPermittedCrossProfileNotificationListeners(admin1);
5012 assertEquals(1, permittedListeners.size());
5013 assertEquals(permittedListener, permittedListeners.get(0));
5014
5015 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5016 assertTrue(dpms.isNotificationListenerServicePermitted(
5017 permittedListener, MANAGED_PROFILE_USER_ID));
5018 assertFalse(dpms.isNotificationListenerServicePermitted(
5019 notPermittedListener, MANAGED_PROFILE_USER_ID));
5020 // System packages are always allowed (even if not in the whitelist)
5021 assertTrue(dpms.isNotificationListenerServicePermitted(
5022 systemListener, MANAGED_PROFILE_USER_ID));
5023
5024 // Setting an empty whitelist - only system listeners allowed
5025 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5026 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005027 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005028 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5029
5030 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5031 assertFalse(dpms.isNotificationListenerServicePermitted(
5032 permittedListener, MANAGED_PROFILE_USER_ID));
5033 assertFalse(dpms.isNotificationListenerServicePermitted(
5034 notPermittedListener, MANAGED_PROFILE_USER_ID));
5035 // System packages are always allowed (even if not in the whitelist)
5036 assertTrue(dpms.isNotificationListenerServicePermitted(
5037 systemListener, MANAGED_PROFILE_USER_ID));
5038
5039 // Setting a null whitelist - all listeners allowed
5040 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5041 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
5042 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5043
5044 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5045 assertTrue(dpms.isNotificationListenerServicePermitted(
5046 permittedListener, MANAGED_PROFILE_USER_ID));
5047 assertTrue(dpms.isNotificationListenerServicePermitted(
5048 notPermittedListener, MANAGED_PROFILE_USER_ID));
5049 assertTrue(dpms.isNotificationListenerServicePermitted(
5050 systemListener, MANAGED_PROFILE_USER_ID));
5051 }
5052
5053 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
5054 throws Exception {
5055 // Set up a managed profile
5056 final int MANAGED_PROFILE_USER_ID = 15;
5057 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
5058 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
5059 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5060
5061 final String nonSystemPackage = "non.system.package";
5062 int appId = 12345;
5063 setupPackageInPackageManager(
5064 nonSystemPackage,
5065 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5066 appId, /*flags=*/ 0);
5067
5068 final String systemListener = "system.package";
5069 setupPackageInPackageManager(
5070 systemListener,
5071 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
5072 ++appId, ApplicationInfo.FLAG_SYSTEM);
5073
5074 // By default all packages are allowed (for all profiles)
5075 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
5076
5077 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5078 assertTrue(dpms.isNotificationListenerServicePermitted(
5079 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5080 assertTrue(dpms.isNotificationListenerServicePermitted(
5081 systemListener, MANAGED_PROFILE_USER_ID));
5082 assertTrue(dpms.isNotificationListenerServicePermitted(
5083 nonSystemPackage, UserHandle.USER_SYSTEM));
5084 assertTrue(dpms.isNotificationListenerServicePermitted(
5085 systemListener, UserHandle.USER_SYSTEM));
5086
5087 // Setting an empty whitelist - only system listeners allowed in managed profile, but
5088 // all allowed in primary profile
5089 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
5090 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01005091 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01005092 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
5093
5094 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5095 assertFalse(dpms.isNotificationListenerServicePermitted(
5096 nonSystemPackage, MANAGED_PROFILE_USER_ID));
5097 assertTrue(dpms.isNotificationListenerServicePermitted(
5098 systemListener, MANAGED_PROFILE_USER_ID));
5099 assertTrue(dpms.isNotificationListenerServicePermitted(
5100 nonSystemPackage, UserHandle.USER_SYSTEM));
5101 assertTrue(dpms.isNotificationListenerServicePermitted(
5102 systemListener, UserHandle.USER_SYSTEM));
5103 }
5104
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005105 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005106 mServiceContext.packageName = mRealTestContext.getPackageName();
5107 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5108 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005109 setDeviceOwner();
5110
Pavel Grafov75c0a892017-05-18 17:28:27 +01005111 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005112 }
5113
5114 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005115 mServiceContext.packageName = mRealTestContext.getPackageName();
5116 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5117 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005118 setAsProfileOwner(admin1);
5119
Pavel Grafov75c0a892017-05-18 17:28:27 +01005120 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
5121 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005122 }
5123
5124 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005125 mServiceContext.packageName = mRealTestContext.getPackageName();
5126 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5127 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005128 setAsProfileOwner(admin1);
5129
Pavel Grafov75c0a892017-05-18 17:28:27 +01005130 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
5131 caller.packageName = "com.example.delegate";
5132 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
5133 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005134
Pavel Grafov75c0a892017-05-18 17:28:27 +01005135 // Make caller a delegated cert installer.
5136 runAsCaller(mAdmin1Context, dpms,
5137 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00005138
5139 verifyCanGetOwnerInstalledCaCerts(null, caller);
5140 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005141 }
5142
Rubin Xucc391c22018-01-02 20:37:35 +00005143 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005144 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5145 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005146 Bundle restriction = new Bundle();
5147 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5148
5149 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5150 RestrictionsListener listener = new RestrictionsListener(mContext);
5151 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
5152 new Bundle());
5153 verifyDataSharingChangedBroadcast();
5154 }
5155
5156 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00005157 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
5158 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00005159 Bundle restriction = new Bundle();
5160 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
5161
5162 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
5163 RestrictionsListener listener = new RestrictionsListener(mContext);
5164 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5165 restriction);
5166 verifyDataSharingChangedBroadcast();
5167 }
5168
5169 public void testDisallowSharingIntoProfileUnchanged() {
5170 RestrictionsListener listener = new RestrictionsListener(mContext);
5171 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
5172 new Bundle());
5173 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
5174 }
5175
5176 private void verifyDataSharingChangedBroadcast() {
5177 Intent expectedIntent = new Intent(
5178 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
5179 expectedIntent.setPackage("com.android.managedprovisioning");
5180 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
5181 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
5182 MockUtils.checkIntent(expectedIntent),
5183 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
5184 }
5185
yuemingwe3d9c092018-01-11 12:11:44 +00005186 public void testOverrideApnAPIsFailWithPO() throws Exception {
5187 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00005188 ApnSetting apn = (new ApnSetting.Builder())
5189 .setApnName("test")
5190 .setEntryName("test")
5191 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
5192 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00005193 assertExpectException(SecurityException.class, null, () ->
5194 dpm.addOverrideApn(admin1, apn));
5195 assertExpectException(SecurityException.class, null, () ->
5196 dpm.updateOverrideApn(admin1, 0, apn));
5197 assertExpectException(SecurityException.class, null, () ->
5198 dpm.removeOverrideApn(admin1, 0));
5199 assertExpectException(SecurityException.class, null, () ->
5200 dpm.getOverrideApns(admin1));
5201 assertExpectException(SecurityException.class, null, () ->
5202 dpm.setOverrideApnsEnabled(admin1, false));
5203 assertExpectException(SecurityException.class, null, () ->
5204 dpm.isOverrideApnEnabled(admin1));
5205 }
5206
Robin Lee2c68dad2017-03-17 12:50:24 +00005207 private void verifyCanGetOwnerInstalledCaCerts(
5208 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005209 final String alias = "cert";
5210 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005211
5212 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005213 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005214 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5215 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005216 }
5217 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5218
5219 // caller: device admin or delegated certificate installer
5220 callerContext.applicationInfo = new ApplicationInfo();
5221 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5222
5223 // system_server
5224 final DpmMockContext serviceContext = mContext;
5225 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005226 getServices().addPackageContext(callerUser, admin1Context);
5227 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005228
5229 // Install a CA cert.
5230 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005231 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005232 .thenReturn(alias);
5233 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005234 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00005235 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00005236 });
5237
Pavel Grafov75c0a892017-05-18 17:28:27 +01005238 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5239 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5240 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005241 flushTasks();
5242
Robin Lee2c68dad2017-03-17 12:50:24 +00005243 final List<String> ownerInstalledCaCerts = new ArrayList<>();
5244
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005245 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00005246 runAsCaller(admin1Context, dpms, (dpm) -> {
5247 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005248 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00005249 ownerInstalledCaCerts.addAll(installedCaCerts);
5250 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005251
5252 // Restarting the DPMS should not lose information.
5253 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01005254 runAsCaller(admin1Context, dpms, (dpm) ->
5255 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005256
5257 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005258 runAsCaller(serviceContext, dpms, (dpm) -> {
5259 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005260
Robin Lee2c68dad2017-03-17 12:50:24 +00005261 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005262 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00005263 });
5264
Pavel Grafov75c0a892017-05-18 17:28:27 +01005265 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5266 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5267 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005268 flushTasks();
5269
5270 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
5271 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00005272 runAsCaller(admin1Context, dpms, (dpm) -> {
5273 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
5274 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005275 }
5276
Robin Lee2c68dad2017-03-17 12:50:24 +00005277 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
5278 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005279 final String alias = "cert";
5280 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00005281
5282 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01005283 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00005284 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
5285 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00005286 }
5287 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
5288
5289 // caller: device admin or delegated certificate installer
5290 callerContext.applicationInfo = new ApplicationInfo();
5291 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
5292
5293 // system_server
5294 final DpmMockContext serviceContext = mContext;
5295 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005296 getServices().addPackageContext(callerUser, admin1Context);
5297 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005298
5299 // Install a CA cert as caller
5300 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005301 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005302 .thenReturn(alias);
5303 assertTrue(dpm.installCaCert(callerName, caCert));
5304 });
5305
5306 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005307 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005308 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005309 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5310 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5311 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005312 flushTasks();
5313
Robin Lee2c68dad2017-03-17 12:50:24 +00005314 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005315 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005316
5317 runAsCaller(serviceContext, dpms, (dpm) -> {
5318 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5319 assertNotNull(ownerInstalledCaCerts);
5320 assertTrue(ownerInstalledCaCerts.isEmpty());
5321 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005322 }
5323
Eran Messeri94d56762017-12-21 20:50:54 +00005324 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5325 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5326 Arrays.sort(gotFlags);
5327 Arrays.sort(expectedFlags);
5328 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5329 }
5330
5331 public void testTranslationOfIdAttestationFlag() {
5332 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5333 int[] correspondingAttUtilsTypes = new int[]{
5334 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5335 AttestationUtils.ID_TYPE_MEID};
5336
5337 // Test translation of zero flags
5338 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5339
5340 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5341 // non-null array
5342 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5343
5344 // Test translation of a single flag
5345 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5346 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5347 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5348
5349 // Test translation of two flags
5350 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5351 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5352 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5353 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5354
5355 // Test translation of all three flags
5356 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5357 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5358 AttestationUtils.ID_TYPE_MEID});
5359 // Test translation of all three flags
5360 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5361 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5362 AttestationUtils.ID_TYPE_MEID});
5363 }
5364
arangelov08d534b2018-01-22 15:20:53 +00005365 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5366 setDeviceOwner();
5367 initializeDpms();
5368 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5369 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5370 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5371 }
5372
5373 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5374 DpmTestUtils.writeInputStreamToFile(
5375 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5376 getDeviceOwnerPoliciesFile());
5377 DpmTestUtils.writeInputStreamToFile(
5378 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5379 getDeviceOwnerFile());
5380 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5381 }
5382
5383 public void testRevertDeviceOwnership_deviceNotMigrated()
5384 throws Exception {
5385 DpmTestUtils.writeInputStreamToFile(
5386 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5387 getDeviceOwnerPoliciesFile());
5388 DpmTestUtils.writeInputStreamToFile(
5389 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5390 getDeviceOwnerFile());
5391 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5392 }
5393
5394 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5395 throws Exception {
5396 DpmTestUtils.writeInputStreamToFile(
5397 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5398 getDeviceOwnerPoliciesFile());
5399 DpmTestUtils.writeInputStreamToFile(
5400 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5401 getDeviceOwnerFile());
5402 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5403 }
5404
5405 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5406 setupProfileOwner();
5407 initializeDpms();
5408 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5409 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5410 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5411 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5412 }
5413
5414 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005415 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5416 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005417 DpmTestUtils.writeInputStreamToFile(
5418 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5419 getProfileOwnerPoliciesFile());
5420 DpmTestUtils.writeInputStreamToFile(
5421 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5422 getProfileOwnerFile());
5423 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5424 }
5425
5426 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005427 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5428 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005429 DpmTestUtils.writeInputStreamToFile(
5430 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5431 getProfileOwnerPoliciesFile());
5432 DpmTestUtils.writeInputStreamToFile(
5433 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5434 getProfileOwnerFile());
5435 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5436 }
5437
5438 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
Alex Johnston755e3772019-11-29 03:27:22 +00005439 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0,
5440 UserManager.USER_TYPE_PROFILE_MANAGED, UserHandle.USER_SYSTEM);
arangelov08d534b2018-01-22 15:20:53 +00005441 DpmTestUtils.writeInputStreamToFile(
5442 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5443 getProfileOwnerPoliciesFile());
5444 DpmTestUtils.writeInputStreamToFile(
5445 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5446 getProfileOwnerFile());
5447 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5448 }
5449
Eran Messeribb271892018-10-17 18:27:50 +01005450 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5451 setupProfileOwner();
5452 configureContextForAccess(mContext, false);
5453
5454 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005455 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005456 }
5457
5458 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5459 setupProfileOwner();
5460 configureContextForAccess(mContext, false);
5461
5462 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005463 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005464 }
5465
5466 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5467 setupProfileOwner();
5468
5469 // This method will throw if the system context could not call
Eran Messeri18d21312019-11-14 22:44:40 +00005470 // markProfileOwnerOfOrganizationOwnedDevice successfully.
5471 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005472 }
5473
Eran Messerib8c46e02019-11-07 12:06:18 +00005474 private void configureContextForAccess(DpmMockContext context, boolean granted) {
Eran Messeribb271892018-10-17 18:27:50 +01005475 when(context.spiedContext.checkCallingPermission(
Eran Messeri18d21312019-11-14 22:44:40 +00005476 permission.MARK_DEVICE_ORGANIZATION_OWNED))
Eran Messeribb271892018-10-17 18:27:50 +01005477 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5478 : PackageManager.PERMISSION_DENIED);
Eran Messerib8c46e02019-11-07 12:06:18 +00005479
5480 when(getServices().userManager.getProfileParent(any()))
5481 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005482 }
5483
5484 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5485 setupProfileOwner();
5486
5487 final long ident = mServiceContext.binder.clearCallingIdentity();
5488 configureContextForAccess(mServiceContext, true);
5489
5490 mServiceContext.binder.callingUid =
5491 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5492 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5493 try {
5494 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005495 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005496 });
5497 } finally {
5498 mServiceContext.binder.restoreCallingIdentity(ident);
5499 }
5500 }
5501
5502 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5503 throws Exception {
5504 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5505 setupDeviceOwner();
5506 configureContextForAccess(mContext, false);
5507
5508 // Device owner should be allowed to request Device ID attestation.
5509 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5510 DpmMockContext.CALLER_SYSTEM_USER_UID);
5511
5512 // Another package must not be allowed to request Device ID attestation.
5513 assertExpectException(SecurityException.class, null,
5514 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5515 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5516 // Another component that is not the admin must not be allowed to request Device ID
5517 // attestation.
5518 assertExpectException(SecurityException.class, null,
5519 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5520 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5521 }
5522
5523 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5524 throws Exception {
5525 configureContextForAccess(mContext, false);
5526
5527 // Make sure a security exception is thrown if the device has no profile owner.
5528 assertExpectException(SecurityException.class, null,
5529 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5530 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5531
5532 setupProfileOwner();
Eran Messeri18d21312019-11-14 22:44:40 +00005533 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005534
5535 // The profile owner is allowed to request Device ID attestation.
5536 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5537 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5538 DpmMockContext.CALLER_UID);
5539 // But not another package.
5540 assertExpectException(SecurityException.class, null,
5541 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5542 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5543 // Or another component which is not the admin.
5544 assertExpectException(SecurityException.class, null,
5545 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5546 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5547 }
5548
5549 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5550 final long ident = mServiceContext.binder.clearCallingIdentity();
5551
5552 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5553 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5554 try {
5555 runAsCaller(mServiceContext, dpms, action);
5556 } finally {
5557 mServiceContext.binder.restoreCallingIdentity(ident);
5558 }
5559 }
5560
5561 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5562 setupProfileOwner();
5563 markDelegatedCertInstallerAsInstalled();
5564
5565 // Configure a delegated cert installer.
5566 runAsCaller(mServiceContext, dpms,
5567 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5568 Arrays.asList(DELEGATION_CERT_INSTALL)));
5569
Eran Messeri18d21312019-11-14 22:44:40 +00005570 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005571
5572 // Make sure that the profile owner can still request Device ID attestation.
5573 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5574 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5575 DpmMockContext.CALLER_UID);
5576
5577 runAsDelegatedCertInstaller(dpm -> {
5578 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5579 DpmMockContext.DELEGATE_PACKAGE_NAME,
5580 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5581 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5582 });
5583 }
5584
5585 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5586 throws Exception {
5587 setupProfileOwner();
5588 markDelegatedCertInstallerAsInstalled();
5589
5590 // Configure a delegated cert installer.
5591 runAsCaller(mServiceContext, dpms,
5592 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5593 Arrays.asList(DELEGATION_CERT_INSTALL)));
5594
5595
5596 assertExpectException(SecurityException.class, null,
5597 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5598 admin1.getPackageName(),
5599 DpmMockContext.CALLER_UID));
5600
5601 runAsDelegatedCertInstaller(dpm -> {
5602 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5603 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5604 DpmMockContext.DELEGATE_PACKAGE_NAME,
5605 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5606 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5607 });
5608 }
5609
Alex Johnston07cb9f02019-11-01 17:40:38 +00005610 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
5611 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5612 setAsProfileOwner(admin1);
5613
Alex Johnston755e3772019-11-29 03:27:22 +00005614 parentDpm.getPasswordComplexity();
Alex Johnston07cb9f02019-11-01 17:40:38 +00005615
5616 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005617 }
5618
5619 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5620 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5621 .thenReturn(false);
5622 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5623 }
5624
5625 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5626 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5627 .thenReturn(true);
5628 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5629 }
5630
5631
5632 public void testGetPasswordComplexity_currentUserNoPassword() {
5633 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5634 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005635 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005636 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5637 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5638
5639 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5640 }
5641
5642 public void testGetPasswordComplexity_currentUserHasPassword() {
5643 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5644 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005645 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005646 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5647 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005648 when(getServices().lockSettingsInternal
5649 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005650 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005651
5652 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5653 }
5654
5655 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5656 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5657 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005658 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005659
5660 UserInfo parentUser = new UserInfo();
5661 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5662 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5663 .thenReturn(parentUser.id);
5664
Rubin Xu19854862019-08-15 16:37:23 +01005665 when(getServices().lockSettingsInternal
5666 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005667 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005668 when(getServices().lockSettingsInternal
5669 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005670 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005671
5672 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5673 }
5674
yuemingwd2bfbc82019-01-02 11:42:25 +00005675 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5676 setAsProfileOwner(admin1);
5677 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5678 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5679 }
5680
5681 public void testCrossProfileCalendarPackages_reopenDpms() {
5682 setAsProfileOwner(admin1);
5683 dpm.setCrossProfileCalendarPackages(admin1, null);
5684 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5685 assertTrue(packages == null);
5686 initializeDpms();
5687 packages = dpm.getCrossProfileCalendarPackages(admin1);
5688 assertTrue(packages == null);
5689
5690 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5691 packages = dpm.getCrossProfileCalendarPackages(admin1);
5692 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5693 initializeDpms();
5694 packages = dpm.getCrossProfileCalendarPackages(admin1);
5695 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5696
5697 final String dummyPackageName = "test";
5698 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5699 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5700 packages = dpm.getCrossProfileCalendarPackages(admin1);
5701 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5702 initializeDpms();
5703 packages = dpm.getCrossProfileCalendarPackages(admin1);
5704 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5705 }
5706
5707 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5708 assertTrue(expected != null);
5709 assertTrue(actual != null);
5710 assertTrue(expected.containsAll(actual));
5711 assertTrue(actual.containsAll(expected));
5712 }
5713
yuemingwdded98f2019-01-30 17:08:12 +00005714 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5715 setAsProfileOwner(admin1);
5716 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5717 when(getServices().settings.settingsSecureGetIntForUser(
5718 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5719 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5720 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5721 }
5722
5723 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5724 final String testPackage = "TEST_PACKAGE";
5725 setAsProfileOwner(admin1);
5726 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5727 when(getServices().settings.settingsSecureGetIntForUser(
5728 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5729 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5730 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5731 }
5732
5733 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5734 final String testPackage = "TEST_PACKAGE";
5735 setAsProfileOwner(admin1);
5736 dpm.setCrossProfileCalendarPackages(admin1, null);
5737 when(getServices().settings.settingsSecureGetIntForUser(
5738 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5739 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5740 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5741 }
5742
Srinivas Paladugu0bb962c2019-10-25 10:03:14 -07005743 public void testSetProtectedPackages_asDO() throws Exception {
5744 final List<String> testPackages = new ArrayList<>();
5745 testPackages.add("package_1");
5746 testPackages.add("package_2");
5747
5748 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5749 setDeviceOwner();
5750
5751 dpm.setProtectedPackages(admin1, testPackages);
5752
5753 verify(getServices().packageManagerInternal).setDeviceOwnerProtectedPackages(testPackages);
5754
5755 assertEquals(testPackages, dpm.getProtectedPackages(admin1));
5756 }
5757
5758 public void testSetProtectedPackages_failingAsPO() throws Exception {
5759 final List<String> testPackages = new ArrayList<>();
5760 testPackages.add("package_1");
5761 testPackages.add("package_2");
5762
5763 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
5764 setAsProfileOwner(admin1);
5765
5766 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5767 () -> dpm.setProtectedPackages(admin1, testPackages));
5768
5769 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5770 () -> dpm.getProtectedPackages(admin1));
5771 }
5772
Eran Messeri18d21312019-11-14 22:44:40 +00005773 private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
Eran Messerib8c46e02019-11-07 12:06:18 +00005774 when(getServices().userManager.getProfileParent(eq(UserHandle.of(userId))))
5775 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005776 final long ident = mServiceContext.binder.clearCallingIdentity();
5777 mServiceContext.binder.callingUid =
5778 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
Eran Messeri18d21312019-11-14 22:44:40 +00005779
5780 configureContextForAccess(mServiceContext, true);
Eran Messeribb271892018-10-17 18:27:50 +01005781 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005782 dpm.markProfileOwnerOnOrganizationOwnedDevice(who);
Eran Messeribb271892018-10-17 18:27:50 +01005783 });
5784 mServiceContext.binder.restoreCallingIdentity(ident);
5785 }
5786
Alex Kershaw434a2242019-12-04 11:34:45 +00005787 public void testGetCrossProfilePackages_notSet_returnsEmpty() {
5788 setAsProfileOwner(admin1);
5789 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
5790 }
5791
5792 public void testGetCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty() {
5793 setAsProfileOwner(admin1);
5794
5795 initializeDpms();
5796
5797 assertTrue(dpm.getCrossProfilePackages(admin1).isEmpty());
5798 }
5799
5800 public void testGetCrossProfilePackages_whenSet_returnsEqual() {
5801 setAsProfileOwner(admin1);
5802 Set<String> packages = Collections.singleton("TEST_PACKAGE");
5803
5804 dpm.setCrossProfilePackages(admin1, packages);
5805
5806 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
5807 }
5808
5809 public void testGetCrossProfilePackages_whenSet_dpmsReinitialized_returnsEqual() {
5810 setAsProfileOwner(admin1);
5811 Set<String> packages = Collections.singleton("TEST_PACKAGE");
5812
5813 dpm.setCrossProfilePackages(admin1, packages);
5814 initializeDpms();
5815
5816 assertEquals(packages, dpm.getCrossProfilePackages(admin1));
5817 }
5818
kholoud mohamedfff05762019-12-10 11:38:04 +00005819 public void testGetAllCrossProfilePackages_notSet_returnsEmpty() throws Exception {
5820 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00005821 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005822
5823 setCrossProfileAppsList();
5824
5825 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
5826 }
5827
5828 public void testGetAllCrossProfilePackages_notSet_dpmsReinitialized_returnsEmpty()
5829 throws Exception {
5830 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
kholoud mohamed79a89f02020-01-15 15:30:07 +00005831 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005832
5833 setCrossProfileAppsList();
5834 initializeDpms();
5835
5836 assertTrue(dpm.getAllCrossProfilePackages().isEmpty());
5837 }
5838
5839 public void testGetAllCrossProfilePackages_whenSet_returnsCombinedSet() throws Exception {
5840 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
5841 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00005842 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005843
5844 dpm.setCrossProfilePackages(admin1, packages);
5845 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
5846
5847 assertEquals(Sets.newSet(
5848 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"),
5849 dpm.getAllCrossProfilePackages());
5850
5851 }
5852
5853 public void testGetAllCrossProfilePackages_whenSet_dpmsReinitialized_returnsCombinedSet()
5854 throws Exception {
5855 addManagedProfile(admin1, mServiceContext.binder.callingUid, admin1);
5856 final Set<String> packages = Sets.newSet("TEST_PACKAGE", "TEST_COMMON_PACKAGE");
kholoud mohamed79a89f02020-01-15 15:30:07 +00005857 mContext.packageName = admin1.getPackageName();
kholoud mohamedfff05762019-12-10 11:38:04 +00005858
5859 dpm.setCrossProfilePackages(admin1, packages);
5860 setCrossProfileAppsList("TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE");
5861 initializeDpms();
5862
5863 assertEquals(Sets.newSet(
5864 "TEST_PACKAGE", "TEST_DEFAULT_PACKAGE", "TEST_COMMON_PACKAGE"),
5865 dpm.getAllCrossProfilePackages());
5866 }
5867
Rubin Xu41bdd972020-01-03 17:18:33 +00005868 public void testSetCommonCriteriaMode_asDeviceOwner() throws Exception {
5869 setDeviceOwner();
5870
5871 dpm.setCommonCriteriaModeEnabled(admin1, true);
5872 verify(getServices().settings).settingsGlobalPutInt(
5873 Settings.Global.COMMON_CRITERIA_MODE, 1);
5874
5875 when(getServices().settings.settingsGlobalGetInt(Settings.Global.COMMON_CRITERIA_MODE, 0))
5876 .thenReturn(1);
5877 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
5878 }
5879
5880 public void testSetCommonCriteriaMode_asPoOfOrgOwnedDevice() throws Exception {
5881 setupProfileOwner();
5882 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
5883
5884 dpm.setCommonCriteriaModeEnabled(admin1, true);
5885 verify(getServices().settings).settingsGlobalPutInt(
5886 Settings.Global.COMMON_CRITERIA_MODE, 1);
5887
5888 when(getServices().settings.settingsGlobalGetInt(Settings.Global.COMMON_CRITERIA_MODE, 0))
5889 .thenReturn(1);
5890 assertTrue(dpm.isCommonCriteriaModeEnabled(admin1));
5891 }
5892
kholoud mohamedfff05762019-12-10 11:38:04 +00005893 private void setCrossProfileAppsList(String... packages) {
5894 when(mContext.getResources()
5895 .getStringArray(eq(R.array.cross_profile_apps)))
5896 .thenReturn(packages);
5897 }
5898
arangelov08d534b2018-01-22 15:20:53 +00005899 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5900 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5901 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5902 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5903
5904 final long ident = mServiceContext.binder.clearCallingIdentity();
5905 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5906 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5907 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5908 // To simulate a reboot, we just reinitialize dpms and call systemReady
5909 initializeDpms();
5910
5911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5912 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5913 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5914 assertTrue(dpm.isAdminActive(admin1));
5915 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5916 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5917
5918 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5919 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5920 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5921 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5922
5923 mServiceContext.binder.restoreCallingIdentity(ident);
5924 }
5925
5926 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5927 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5928 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5929 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5930
5931 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5932 DpmMockContext.CALLER_SYSTEM_USER_UID);
5933 setUpPackageManagerForAdmin(admin1, uid);
5934 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5935 // To simulate a reboot, we just reinitialize dpms and call systemReady
5936 initializeDpms();
5937
5938 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5939 assertTrue(dpm.isAdminActive(admin1));
5940 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5941 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5942 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5943 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5944 }
5945
5946 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5947 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5948 metadataManager.deleteMetadataFile();
5949
5950 final TransferOwnershipMetadataManager.Metadata metadata =
5951 new TransferOwnershipMetadataManager.Metadata(
5952 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5953 callerUserHandle,
5954 adminType);
5955 metadataManager.saveMetadataFile(metadata);
5956 }
5957
5958 private File getDeviceOwnerFile() {
5959 return dpms.mOwners.getDeviceOwnerFile();
5960 }
5961
5962 private File getProfileOwnerFile() {
5963 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5964 }
5965
5966 private File getProfileOwnerPoliciesFile() {
5967 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5968 DpmMockContext.CALLER_USER_HANDLE);
5969 return getPoliciesFile(parentDir);
5970 }
5971
5972 private File getDeviceOwnerPoliciesFile() {
5973 return getPoliciesFile(getServices().systemUserDataDir);
5974 }
5975
5976 private File getPoliciesFile(File parentDir) {
5977 return new File(parentDir, "device_policies.xml");
5978 }
5979
Victor Chang3e794af2016-03-04 13:48:17 +00005980 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005981 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005982 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5983 dpms.notifyChangeToContentObserver(
5984 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5985 }
5986
5987 private void assertProvisioningAllowed(String action, boolean expected) {
5988 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5989 dpm.isProvisioningAllowed(action));
5990 }
Tony Mak2f26b792016-11-28 17:54:51 +00005991
Nicolas Prevot45d29072017-01-18 16:11:19 +00005992 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5993 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005994 final String previousPackageName = mContext.packageName;
5995 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005996
5997 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5998 mContext.packageName = packageName;
5999 mMockContext.binder.callingUid = uid;
6000 assertProvisioningAllowed(action, expected);
6001
6002 // Set the previous package name / calling uid to go back to the initial state.
6003 mContext.packageName = previousPackageName;
6004 mMockContext.binder.callingUid = previousUid;
6005 }
6006
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006007 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00006008 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
6009 }
6010
6011 private void assertCheckProvisioningPreCondition(
6012 String action, String packageName, int provisioningCondition) {
6013 assertEquals("checkProvisioningPreCondition("
6014 + action + ", " + packageName + ") returning unexpected result",
6015 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00006016 }
6017
Tony Mak2f26b792016-11-28 17:54:51 +00006018 /**
6019 * Setup a managed profile with the specified admin and its uid.
6020 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
6021 * @param adminUid uid of the admin package.
6022 * @param copyFromAdmin package information for {@code admin} will be built based on this
6023 * component's information.
6024 */
6025 private void addManagedProfile(
6026 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
6027 final int userId = UserHandle.getUserId(adminUid);
Alex Johnston755e3772019-11-29 03:27:22 +00006028 getServices().addUser(userId, 0, UserManager.USER_TYPE_PROFILE_MANAGED,
6029 UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00006030 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
6031 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
6032 dpm.setActiveAdmin(admin, false, userId);
6033 assertTrue(dpm.setProfileOwner(admin, null, userId));
6034 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
6035 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00006036
6037 /**
Robin Leeabaa0692017-02-20 20:54:22 +00006038 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00006039 */
Robin Leeabaa0692017-02-20 20:54:22 +00006040 private static StringParceledListSlice asSlice(String[] s) {
6041 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00006042 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006043
6044 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00006045 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
6046 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006047
Robin Lee2c68dad2017-03-17 12:50:24 +00006048 // We can't let exceptions happen on the background thread. Throw them here if they happen
6049 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01006050 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01006051 }
Victor Chang3e794af2016-03-04 13:48:17 +00006052}