blob: 9ae9824da3e2bc73761d8f7a0245e9db8e122b0b [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6a40f092016-10-25 15:46:51 +010028import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
29import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
30import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
31
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080032import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070033import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010034
Pavel Grafov75c0a892017-05-18 17:28:27 +010035import static org.mockito.Matchers.any;
36import static org.mockito.Matchers.anyInt;
37import static org.mockito.Matchers.anyLong;
38import static org.mockito.Matchers.anyObject;
39import static org.mockito.Matchers.anyString;
40import static org.mockito.Matchers.eq;
41import static org.mockito.Matchers.isNull;
42import static org.mockito.Mockito.atLeast;
43import static org.mockito.Mockito.doAnswer;
44import static org.mockito.Mockito.doReturn;
45import static org.mockito.Mockito.never;
46import static org.mockito.Mockito.nullable;
47import static org.mockito.Mockito.reset;
48import static org.mockito.Mockito.timeout;
49import static org.mockito.Mockito.times;
50import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080051import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010052import static org.mockito.Mockito.verifyZeroInteractions;
53import static org.mockito.Mockito.when;
54import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000055import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010056
Makoto Onukif76b06a2015-09-22 15:03:44 -070057import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000058import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070059import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010060import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000061import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070062import android.app.admin.DeviceAdminReceiver;
63import android.app.admin.DevicePolicyManager;
64import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010065import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070066import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070067import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000068import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000069import android.content.pm.ApplicationInfo;
70import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010072import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000073import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000074import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010075import android.graphics.Color;
76import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080077import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070078import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080079import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070080import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070081import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010082import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080083import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010084import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000085import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000086import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000087import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080088import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010089import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070090import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070091
Pavel Grafov57f1b662019-03-27 14:55:38 +000092import androidx.test.filters.SmallTest;
93
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010094import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000095import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000096import com.android.server.LocalServices;
97import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000098import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000099import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100
Robin Lee7f5c91c2017-02-08 21:27:02 +0000101import org.hamcrest.BaseMatcher;
102import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800103import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700104import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700105
arangelov08d534b2018-01-22 15:20:53 +0000106import java.io.File;
107import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800108import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000109import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000110import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700111import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700113import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100114import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000115import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700118 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000119 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120 m FrameworksServicesTests &&
121 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000122 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700123 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700124 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125
126 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000127 *
128 * , or:
129 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700130 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000131@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100132@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700133public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000134 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
135 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
136 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100137 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800138 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100139 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000140
Pavel Grafov75c0a892017-05-18 17:28:27 +0100141 // TODO replace all instances of this with explicit {@link #mServiceContext}.
142 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700143 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100144
145 private DpmMockContext mServiceContext;
146 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700147 public DevicePolicyManager dpm;
148 public DevicePolicyManagerServiceTestable dpms;
149
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100150 /*
151 * The CA cert below is the content of cacert.pem as generated by:
152 *
153 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
154 */
155 private static final String TEST_CA =
156 "-----BEGIN CERTIFICATE-----\n" +
157 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
158 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
159 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
160 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
161 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
162 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
163 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
164 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
165 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
166 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
167 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
168 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
169 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
170 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
171 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
172 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
173 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
174 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
175 "wQ==\n" +
176 "-----END CERTIFICATE-----\n";
177
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700178 @Override
179 protected void setUp() throws Exception {
180 super.setUp();
181
182 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100183 mServiceContext = mContext;
184 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
185 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700186 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100187 doReturn(Collections.singletonList(new ResolveInfo()))
188 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
189 any(Intent.class),
190 anyInt(),
191 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700192
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800193 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100194 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800195
Makoto Onukia52562c2015-10-01 16:12:31 -0700196 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700197
Sudheer Shanka101c3532018-01-08 16:28:42 -0800198 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800199 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700200 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
201 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
202 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800203 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700204
Pavel Grafov75c0a892017-05-18 17:28:27 +0100205 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
206 mAdmin1Context.packageName = admin1.getPackageName();
207 mAdmin1Context.applicationInfo = new ApplicationInfo();
208 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
209
Makoto Onukib643fb02015-09-22 15:03:44 -0700210 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100211
212 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700213 }
214
arangelov08d534b2018-01-22 15:20:53 +0000215 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
216 return dpms.mTransferOwnershipMetadataManager;
217 }
218
Robin Lee2c68dad2017-03-17 12:50:24 +0000219 @Override
220 protected void tearDown() throws Exception {
221 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000222 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000223 super.tearDown();
224 }
225
Makoto Onukia52562c2015-10-01 16:12:31 -0700226 private void initializeDpms() {
227 // Need clearCallingIdentity() to pass permission checks.
228 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100229 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700230
Pavel Grafov75c0a892017-05-18 17:28:27 +0100231 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
232 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
233 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700234
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700236
Pavel Grafov75c0a892017-05-18 17:28:27 +0100237 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700238 }
239
Makoto Onukib643fb02015-09-22 15:03:44 -0700240 private void setUpUserManager() {
241 // Emulate UserManager.set/getApplicationRestriction().
242 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
243
244 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000245 doAnswer((Answer<Void>) invocation -> {
246 String pkg = (String) invocation.getArguments()[0];
247 Bundle bundle = (Bundle) invocation.getArguments()[1];
248 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700249
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000250 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700251
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000252 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100253 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100254 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
256 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000257 doAnswer((Answer<Bundle>) invocation -> {
258 String pkg = (String) invocation.getArguments()[0];
259 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700260
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000261 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100262 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700263 anyString(), any(UserHandle.class));
264
Makoto Onukid932f762015-09-29 16:53:38 -0700265 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100266 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700267 }
268
269 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700271
Pavel Grafov75c0a892017-05-18 17:28:27 +0100272 mServiceContext.binder.callingUid =
273 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
274 runAsCaller(mServiceContext, dpms, dpm -> {
275 // PO needs to be a DA.
276 dpm.setActiveAdmin(admin, /*replace=*/ false);
277 // Fire!
278 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
279 // Check
280 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
281 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700282
Pavel Grafov75c0a892017-05-18 17:28:27 +0100283 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700284 }
285
286 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100287 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700288 .thenReturn(false);
289
290 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100291 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292
293 // If the device has no DPMS feature, it shouldn't register the local service.
294 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
295 }
296
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800297 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800298 // Device owner in SYSTEM_USER
299 setDeviceOwner();
300 // Profile owner in CALLER_USER_HANDLE
301 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
302 setAsProfileOwner(admin2);
303 // Active admin in CALLER_USER_HANDLE
304 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
305 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
306 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
307 DpmMockContext.CALLER_USER_HANDLE);
308 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
309 DpmMockContext.CALLER_USER_HANDLE));
310
311 initializeDpms();
312
313 // Verify
314 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800315 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800316 eq(UserHandle.USER_SYSTEM));
317 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800318 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800319 adminAnotherPackage.getPackageName()),
320 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800321 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
322 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
323 }
324
325 public void testLoadAdminData_noAdmins() throws Exception {
326 final int ANOTHER_USER_ID = 15;
327 getServices().addUser(ANOTHER_USER_ID, 0);
328
329 initializeDpms();
330
331 // Verify
332 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
333 null, DpmMockContext.CALLER_USER_HANDLE);
334 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
335 null, ANOTHER_USER_ID);
336 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
337 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800338 }
339
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700340 /**
341 * Caller doesn't have proper permissions.
342 */
343 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344 // 1. Failure cases.
345
346 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100347 assertExpectException(SecurityException.class, /* messageRegex= */ null,
348 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700349
350 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
351 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100352
353 assertExpectException(SecurityException.class, /* messageRegex= */ null,
354 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700355 }
356
Makoto Onukif76b06a2015-09-22 15:03:44 -0700357 /**
358 * Test for:
359 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800360 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 * {@link DevicePolicyManager#isAdminActive}
362 * {@link DevicePolicyManager#isAdminActiveAsUser}
363 * {@link DevicePolicyManager#getActiveAdmins}
364 * {@link DevicePolicyManager#getActiveAdminsAsUser}
365 */
366 public void testSetActiveAdmin() throws Exception {
367 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700368 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
369
Makoto Onukif76b06a2015-09-22 15:03:44 -0700370 // 2. Call the API.
371 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700372
373 // 3. Verify internal calls.
374
375 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700376 verify(mContext.spiedContext).sendBroadcastAsUser(
377 MockUtils.checkIntentAction(
378 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
379 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
380 verify(mContext.spiedContext).sendBroadcastAsUser(
381 MockUtils.checkIntentAction(
382 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100383 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
384 eq(null),
385 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700386
Pavel Grafov75c0a892017-05-18 17:28:27 +0100387 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700388 eq(admin1.getPackageName()),
389 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
390 eq(PackageManager.DONT_KILL_APP),
391 eq(DpmMockContext.CALLER_USER_HANDLE),
392 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700393
Sudheer Shanka101c3532018-01-08 16:28:42 -0800394 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
395 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
396
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700397 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700398
399 // Make sure it's active admin1.
400 assertTrue(dpm.isAdminActive(admin1));
401 assertFalse(dpm.isAdminActive(admin2));
402 assertFalse(dpm.isAdminActive(admin3));
403
404 // But not admin1 for a different user.
405
406 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
407 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
408 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
409
410 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
411 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
412
413 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
414
415 // Next, add one more admin.
416 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700417 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700418 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700419
420 dpm.setActiveAdmin(admin2, /* replace =*/ false);
421
422 // Now we have two admins.
423 assertTrue(dpm.isAdminActive(admin1));
424 assertTrue(dpm.isAdminActive(admin2));
425 assertFalse(dpm.isAdminActive(admin3));
426
427 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
428 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100429 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700430 eq(admin1.getPackageName()),
431 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
432 eq(PackageManager.DONT_KILL_APP),
433 eq(DpmMockContext.CALLER_USER_HANDLE),
434 anyString());
435
Sudheer Shanka101c3532018-01-08 16:28:42 -0800436 // times(2) because it was previously called for admin1 which is in the same package
437 // as admin2.
438 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
439 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
440
Makoto Onukif76b06a2015-09-22 15:03:44 -0700441 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100442 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
443 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700444
445 // 5. Add the same admin1 again with replace, which should succeed.
446 dpm.setActiveAdmin(admin1, /* replace =*/ true);
447
448 // TODO make sure it's replaced.
449
450 // 6. Test getActiveAdmins()
451 List<ComponentName> admins = dpm.getActiveAdmins();
452 assertEquals(2, admins.size());
453 assertEquals(admin1, admins.get(0));
454 assertEquals(admin2, admins.get(1));
455
Sudheer Shanka101c3532018-01-08 16:28:42 -0800456 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
457 // replaced
458 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
459
Makoto Onukif76b06a2015-09-22 15:03:44 -0700460 // Another user has no admins.
461 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
462
463 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
464 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
465
466 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
467 }
468
Makoto Onukid932f762015-09-29 16:53:38 -0700469 public void testSetActiveAdmin_multiUsers() throws Exception {
470
471 final int ANOTHER_USER_ID = 100;
472 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
473
Pavel Grafov75c0a892017-05-18 17:28:27 +0100474 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700475
476 // Set up pacakge manager for the other user.
477 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700478
479 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
480
481 dpm.setActiveAdmin(admin1, /* replace =*/ false);
482
483 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
484 dpm.setActiveAdmin(admin2, /* replace =*/ false);
485
486
487 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
488 assertTrue(dpm.isAdminActive(admin1));
489 assertFalse(dpm.isAdminActive(admin2));
490
491 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
492 assertFalse(dpm.isAdminActive(admin1));
493 assertTrue(dpm.isAdminActive(admin2));
494 }
495
Makoto Onukif76b06a2015-09-22 15:03:44 -0700496 /**
497 * Test for:
498 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800499 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700500 */
501 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
502 // 1. Make sure the caller has proper permissions.
503 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
504
505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
506 assertTrue(dpm.isAdminActive(admin1));
507
508 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100509 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
510 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700511 }
512
513 /**
514 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800515 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
516 * BIND_DEVICE_ADMIN.
517 */
518 public void testSetActiveAdmin_permissionCheck() throws Exception {
519 // 1. Make sure the caller has proper permissions.
520 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
521
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100522 assertExpectException(IllegalArgumentException.class,
523 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
524 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800525 assertFalse(dpm.isAdminActive(adminNoPerm));
526
527 // Change the target API level to MNC. Now it can be set as DA.
528 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
529 VERSION_CODES.M);
530 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
531 assertTrue(dpm.isAdminActive(adminNoPerm));
532
533 // TODO Test the "load from the file" case where DA will still be loaded even without
534 // BIND_DEVICE_ADMIN and target API is N.
535 }
536
537 /**
538 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700539 * {@link DevicePolicyManager#removeActiveAdmin}
540 */
541 public void testRemoveActiveAdmin_SecurityException() {
542 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
543
544 // Add admin.
545
546 dpm.setActiveAdmin(admin1, /* replace =*/ false);
547
548 assertTrue(dpm.isAdminActive(admin1));
549
550 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
551
552 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100553 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
554 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700555
556 // Try to remove active admin with a different caller userid should fail too, without
557 // having MANAGE_DEVICE_ADMINS.
558 mContext.callerPermissions.clear();
559
Makoto Onukid932f762015-09-29 16:53:38 -0700560 // Change the caller, and call into DPMS directly with a different user-id.
561
Makoto Onukif76b06a2015-09-22 15:03:44 -0700562 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100563 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
564 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700565 }
566
567 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800568 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
569 * (because we can't send the remove broadcast).
570 */
571 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
572 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
573
574 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
575
576 // Add admin.
577
578 dpm.setActiveAdmin(admin1, /* replace =*/ false);
579
580 assertTrue(dpm.isAdminActive(admin1));
581
582 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
583
584 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100585 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800586 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100587 assertExpectException(IllegalStateException.class,
588 /* messageRegex= */ "User must be running and unlocked",
589 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590
591 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800592 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
593 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800594
595 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100596 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800597 .thenReturn(true);
598
599 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700600 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800601 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
602 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800603 }
604
605 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700606 * Test for:
607 * {@link DevicePolicyManager#removeActiveAdmin}
608 */
Makoto Onukid932f762015-09-29 16:53:38 -0700609 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700610 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
611
612 // Add admin1.
613
614 dpm.setActiveAdmin(admin1, /* replace =*/ false);
615
616 assertTrue(dpm.isAdminActive(admin1));
617 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
618
619 // Different user, but should work, because caller has proper permissions.
620 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700621
622 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700623 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700624
625 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700626 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800627 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
628 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700629
630 // TODO DO Still can't be removed in this case.
631 }
632
633 /**
634 * Test for:
635 * {@link DevicePolicyManager#removeActiveAdmin}
636 */
637 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
638 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
639 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
640
641 // Add admin1.
642
643 dpm.setActiveAdmin(admin1, /* replace =*/ false);
644
645 assertTrue(dpm.isAdminActive(admin1));
646 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
647
648 // Broadcast from saveSettingsLocked().
649 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
650 MockUtils.checkIntentAction(
651 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
652 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
653
654 // Remove. No permissions, but same user, so it'll work.
655 mContext.callerPermissions.clear();
656 dpm.removeActiveAdmin(admin1);
657
Makoto Onukif76b06a2015-09-22 15:03:44 -0700658 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
659 MockUtils.checkIntentAction(
660 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
661 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
662 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100663 eq(AppOpsManager.OP_NONE),
664 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700665 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700666 eq(dpms.mHandler),
667 eq(Activity.RESULT_OK),
668 isNull(String.class),
669 isNull(Bundle.class));
670
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700671 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800672 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
673 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700674
675 // Again broadcast from saveSettingsLocked().
676 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
677 MockUtils.checkIntentAction(
678 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
679 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
680
681 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700682 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700683
Sudheer Shanka101c3532018-01-08 16:28:42 -0800684 public void testRemoveActiveAdmin_multipleAdminsInUser() {
685 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
686 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
687
688 // Add admin1.
689 dpm.setActiveAdmin(admin1, /* replace =*/ false);
690
691 assertTrue(dpm.isAdminActive(admin1));
692 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
693
694 // Add admin2.
695 dpm.setActiveAdmin(admin2, /* replace =*/ false);
696
697 assertTrue(dpm.isAdminActive(admin2));
698 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
699
700 // Broadcast from saveSettingsLocked().
701 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
702 MockUtils.checkIntentAction(
703 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
704 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
705
706 // Remove. No permissions, but same user, so it'll work.
707 mContext.callerPermissions.clear();
708 dpm.removeActiveAdmin(admin1);
709
710 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
711 MockUtils.checkIntentAction(
712 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
713 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
714 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100715 eq(AppOpsManager.OP_NONE),
716 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800717 any(BroadcastReceiver.class),
718 eq(dpms.mHandler),
719 eq(Activity.RESULT_OK),
720 isNull(String.class),
721 isNull(Bundle.class));
722
723 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
724 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800725 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800726 eq(DpmMockContext.CALLER_USER_HANDLE));
727
728 // Again broadcast from saveSettingsLocked().
729 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
730 MockUtils.checkIntentAction(
731 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
732 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
733 }
734
735 /**
736 * Test for:
737 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
738 */
739 public void testForceRemoveActiveAdmin() throws Exception {
740 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
741
742 // Add admin.
743 setupPackageInPackageManager(admin1.getPackageName(),
744 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
745 /* appId= */ 10138,
746 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
747 dpm.setActiveAdmin(admin1, /* replace =*/ false);
748 assertTrue(dpm.isAdminActive(admin1));
749
750 // Calling from a non-shell uid should fail with a SecurityException
751 mContext.binder.callingUid = 123456;
752 assertExpectException(SecurityException.class,
753 /* messageRegex =*/ "Non-shell user attempted to call",
754 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
755
756 mContext.binder.callingUid = Process.SHELL_UID;
757 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
758
759 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
760 // Verify
761 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
762 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
763 null, DpmMockContext.CALLER_USER_HANDLE);
764 }
765
Makoto Onukib643fb02015-09-22 15:03:44 -0700766 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000767 * Test for: @{link DevicePolicyManager#setActivePasswordState}
768 *
769 * Validates that when the password for a user changes, the notification broadcast intent
770 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
771 * addition to ones in the original user.
772 */
773 public void testSetActivePasswordState_sendToProfiles() throws Exception {
774 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
775
776 final int MANAGED_PROFILE_USER_ID = 78;
777 final int MANAGED_PROFILE_ADMIN_UID =
778 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
779
780 // Setup device owner.
781 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
782 mContext.packageName = admin1.getPackageName();
783 setupDeviceOwner();
784
785 // Add a managed profile belonging to the system user.
786 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
787
788 // Change the parent user's password.
789 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
790
791 // Both the device owner and the managed profile owner should receive this broadcast.
792 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
793 intent.setComponent(admin1);
794 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
795
796 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
797 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100798 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
799 eq(null),
800 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000801 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
802 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100803 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
804 eq(null),
805 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000806 }
807
808 /**
809 * Test for: @{link DevicePolicyManager#setActivePasswordState}
810 *
811 * Validates that when the password for a managed profile changes, the notification broadcast
812 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
813 * its parent.
814 */
815 public void testSetActivePasswordState_notSentToParent() throws Exception {
816 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
817
818 final int MANAGED_PROFILE_USER_ID = 78;
819 final int MANAGED_PROFILE_ADMIN_UID =
820 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
821
822 // Setup device owner.
823 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
824 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100825 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000826 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
827 setupDeviceOwner();
828
829 // Add a managed profile belonging to the system user.
830 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
831
832 // Change the profile's password.
833 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
834
835 // Both the device owner and the managed profile owner should receive this broadcast.
836 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
837 intent.setComponent(admin1);
838 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
839
840 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
841 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100842 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
843 eq(null),
844 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000845 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
846 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100847 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
848 eq(null),
849 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000850 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100851
Robin Leed2a73ed2016-12-19 09:07:16 +0000852 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000853 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700854 */
855 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000856 setDeviceOwner();
857
858 // Try to set a profile owner on the same user, which should fail.
859 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
860 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100861 assertExpectException(IllegalStateException.class,
862 /* messageRegex= */ "already has a device owner",
863 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000864
865 // DO admin can't be deactivated.
866 dpm.removeActiveAdmin(admin1);
867 assertTrue(dpm.isAdminActive(admin1));
868
869 // TODO Test getDeviceOwnerName() too. To do so, we need to change
870 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
871 }
872
873 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700874 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800875 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700876 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
877 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
878
Makoto Onukid932f762015-09-29 16:53:38 -0700879 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700880 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
881
Makoto Onukid932f762015-09-29 16:53:38 -0700882 // Make sure admin1 is installed on system user.
883 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700884
Makoto Onukic8a5a552015-11-19 14:29:12 -0800885 // Check various get APIs.
886 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
887
Makoto Onukib643fb02015-09-22 15:03:44 -0700888 // DO needs to be an DA.
889 dpm.setActiveAdmin(admin1, /* replace =*/ false);
890
891 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700892 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700893
Makoto Onukic8a5a552015-11-19 14:29:12 -0800894 // getDeviceOwnerComponent should return the admin1 component.
895 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
896 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
897
898 // Check various get APIs.
899 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
900
901 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
902 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
903 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
904 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
905
906 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
907
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000908 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100909 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000910 eq(admin1.getPackageName()));
911
Makoto Onukib643fb02015-09-22 15:03:44 -0700912 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100913 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700914 eq(UserHandle.USER_SYSTEM), eq(false));
915
916 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
917 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
918 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
919
Makoto Onukic8a5a552015-11-19 14:29:12 -0800920 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700921 }
922
Makoto Onukic8a5a552015-11-19 14:29:12 -0800923 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
924 final int origCallingUser = mContext.binder.callingUid;
925 final List origPermissions = new ArrayList(mContext.callerPermissions);
926 mContext.callerPermissions.clear();
927
928 mContext.callerPermissions.add(permission.MANAGE_USERS);
929
930 mContext.binder.callingUid = Process.SYSTEM_UID;
931
932 // TODO Test getDeviceOwnerName() too. To do so, we need to change
933 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
934 if (hasDeviceOwner) {
935 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
936 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
937 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
938
939 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
940 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
941 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
942 } else {
943 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
944 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
945 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
946
947 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
948 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
949 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
950 }
951
952 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
953 if (hasDeviceOwner) {
954 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
955 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
956 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
957
958 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
959 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
960 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
961 } else {
962 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
963 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
964 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
965
966 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
967 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
968 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
969 }
970
971 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
972 // Still with MANAGE_USERS.
973 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
974 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
975 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
976
977 if (hasDeviceOwner) {
978 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
980 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
981 } else {
982 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
983 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
984 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
985 }
986
987 mContext.binder.callingUid = Process.SYSTEM_UID;
988 mContext.callerPermissions.remove(permission.MANAGE_USERS);
989 // System can still call "OnAnyUser" without MANAGE_USERS.
990 if (hasDeviceOwner) {
991 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
992 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
993 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
994
995 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
996 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
997 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
998 } else {
999 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1000 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1001 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1002
1003 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1004 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1005 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1006 }
1007
1008 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1009 // Still no MANAGE_USERS.
1010 if (hasDeviceOwner) {
1011 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1012 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1013 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1014 } else {
1015 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1016 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1017 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1018 }
1019
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001020 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1021 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1022 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1023 dpm::getDeviceOwnerComponentOnAnyUser);
1024 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1025 dpm::getDeviceOwnerUserId);
1026 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1027 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001028
1029 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1030 // Still no MANAGE_USERS.
1031 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1032 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1033 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1034
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001035 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1036 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1037 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1038 dpm::getDeviceOwnerComponentOnAnyUser);
1039 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1040 dpm::getDeviceOwnerUserId);
1041 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1042 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001043
1044 // Restore.
1045 mContext.binder.callingUid = origCallingUser;
1046 mContext.callerPermissions.addAll(origPermissions);
1047 }
1048
1049
Makoto Onukib643fb02015-09-22 15:03:44 -07001050 /**
1051 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1052 */
1053 public void testSetDeviceOwner_noSuchPackage() {
1054 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001055 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001056 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1057 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1058
1059 // Call from a process on the system user.
1060 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1061
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001062 assertExpectException(IllegalArgumentException.class,
1063 /* messageRegex= */ "Invalid component",
1064 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001065 }
1066
1067 public void testSetDeviceOwner_failures() throws Exception {
1068 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1069 }
1070
Makoto Onukia52562c2015-10-01 16:12:31 -07001071 public void testClearDeviceOwner() throws Exception {
1072 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001073 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001074 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1075 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1076
1077 // Set admin1 as a DA to the secondary user.
1078 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1079
1080 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1081
1082 // Set admin 1 as the DO to the system user.
1083
1084 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1085 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1086 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1087 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1088
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001089 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001090 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001091 eq(admin1.getPackageName()));
1092
Makoto Onukic8a5a552015-11-19 14:29:12 -08001093 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001094
Makoto Onuki90b89652016-01-28 14:44:18 -08001095 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001096 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001097 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001098
1099 assertTrue(dpm.isAdminActive(admin1));
1100 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1101
Makoto Onukia52562c2015-10-01 16:12:31 -07001102 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001103 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001104
1105 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001106 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1107 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001108
1109 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001110 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001111 assertExpectException(IllegalStateException.class,
1112 /* messageRegex= */ "User must be running and unlocked",
1113 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001114
Pavel Grafov75c0a892017-05-18 17:28:27 +01001115 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1116 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1118
1119 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001120 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001121
Pavel Grafov75c0a892017-05-18 17:28:27 +01001122 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001123 eq(false),
1124 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1125
Pavel Grafov75c0a892017-05-18 17:28:27 +01001126 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001127 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001128 eq(null),
1129 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001130
Sudheer Shanka101c3532018-01-08 16:28:42 -08001131 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1132 null, UserHandle.USER_SYSTEM);
1133
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001134 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001135
1136 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1137 // and once for clearing it.
1138 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1139 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1140 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001141 // TODO Check other calls.
1142 }
1143
1144 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1145 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001146 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001147 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1148 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1149
1150 // Set admin1 as a DA to the secondary user.
1151 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1152
1153 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1154
1155 // Set admin 1 as the DO to the system user.
1156
1157 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1158 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1159 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1160 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1161
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001162 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001163 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001164 eq(admin1.getPackageName()));
1165
Makoto Onukic8a5a552015-11-19 14:29:12 -08001166 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001167
1168 // Now call clear from the secondary user, which should throw.
1169 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1170
1171 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001172 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001173 eq(admin1.getPackageName()),
1174 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001175 assertExpectException(SecurityException.class,
1176 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1177 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001178
Makoto Onukic8a5a552015-11-19 14:29:12 -08001179 // DO shouldn't be removed.
1180 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001181 }
1182
Makoto Onukib643fb02015-09-22 15:03:44 -07001183 public void testSetProfileOwner() throws Exception {
1184 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001185
Makoto Onuki90b89652016-01-28 14:44:18 -08001186 // PO admin can't be deactivated.
1187 dpm.removeActiveAdmin(admin1);
1188 assertTrue(dpm.isAdminActive(admin1));
1189
Makoto Onuki803d6752015-10-30 12:58:39 -07001190 // Try setting DO on the same user, which should fail.
1191 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001192 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1193 runAsCaller(mServiceContext, dpms, dpm -> {
1194 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001195 assertExpectException(IllegalStateException.class,
1196 /* messageRegex= */ "already has a profile owner",
1197 () -> dpm.setDeviceOwner(admin2, "owner-name",
1198 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001199 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001200 }
1201
Makoto Onuki90b89652016-01-28 14:44:18 -08001202 public void testClearProfileOwner() throws Exception {
1203 setAsProfileOwner(admin1);
1204
1205 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1206
1207 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1208 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1209
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001210 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001211 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001212 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001213 assertExpectException(IllegalStateException.class,
1214 /* messageRegex= */ "User must be running and unlocked",
1215 () -> dpm.clearProfileOwner(admin1));
1216
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001217 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001218 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001219 dpm.clearProfileOwner(admin1);
1220
1221 // Check
1222 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001223 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001224 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1225 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001226 }
1227
Makoto Onukib643fb02015-09-22 15:03:44 -07001228 public void testSetProfileOwner_failures() throws Exception {
1229 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1230 }
1231
Makoto Onukia52562c2015-10-01 16:12:31 -07001232 public void testGetDeviceOwnerAdminLocked() throws Exception {
1233 checkDeviceOwnerWithMultipleDeviceAdmins();
1234 }
1235
1236 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1237 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1238 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1239 // make sure it gets the right component from the right user.
1240
1241 final int ANOTHER_USER_ID = 100;
1242 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1243
Pavel Grafov75c0a892017-05-18 17:28:27 +01001244 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001245
1246 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001247 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001248 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1249 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1250
1251 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1252
Pavel Grafov75c0a892017-05-18 17:28:27 +01001253 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001254
Makoto Onukia52562c2015-10-01 16:12:31 -07001255 // Make sure the admin packge is installed to each user.
1256 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1257 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1258
1259 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1260 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1261
1262 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1263
1264
1265 // Set active admins to the users.
1266 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1267 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1268
1269 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1270 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1271
1272 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1273
1274 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001275 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001276 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1277
Makoto Onukic8a5a552015-11-19 14:29:12 -08001278 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001279
1280 // Then check getDeviceOwnerAdminLocked().
1281 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1282 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1283 }
1284
1285 /**
1286 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001287 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1288 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001289 *
1290 * We didn't use to persist the DO component class name, but now we do, and the above method
1291 * finds the right component from a package name upon migration.
1292 */
1293 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001294 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001295 checkDeviceOwnerWithMultipleDeviceAdmins();
1296
1297 // Overwrite the device owner setting and clears the clas name.
1298 dpms.mOwners.setDeviceOwner(
1299 new ComponentName(admin2.getPackageName(), ""),
1300 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1301 dpms.mOwners.writeDeviceOwner();
1302
1303 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001304 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001305
1306 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001307 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001308 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001309 initializeDpms();
1310
1311 // Now the DO component name is a full name.
1312 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1313 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001314 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001315 }
1316
Makoto Onukib643fb02015-09-22 15:03:44 -07001317 public void testSetGetApplicationRestriction() {
1318 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001319 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001320
1321 {
1322 Bundle rest = new Bundle();
1323 rest.putString("KEY_STRING", "Foo1");
1324 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1325 }
1326
1327 {
1328 Bundle rest = new Bundle();
1329 rest.putString("KEY_STRING", "Foo2");
1330 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1331 }
1332
1333 {
1334 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1335 assertNotNull(returned);
1336 assertEquals(returned.size(), 1);
1337 assertEquals(returned.get("KEY_STRING"), "Foo1");
1338 }
1339
1340 {
1341 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1342 assertNotNull(returned);
1343 assertEquals(returned.size(), 1);
1344 assertEquals(returned.get("KEY_STRING"), "Foo2");
1345 }
1346
1347 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1348 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1349 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001350
Edman Anjosf9946772016-11-28 16:35:15 +01001351 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001352 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1353 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001354 *
1355 * @param packageName the name of the package to be setup
1356 * @param appId the application ID to be given to the package
1357 * @return the UID of the package as known by the mock package manager
1358 */
1359 private int setupPackageInPackageManager(final String packageName, final int appId)
1360 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001361 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001362 ApplicationInfo.FLAG_HAS_CODE);
1363 }
1364
1365 /**
1366 * Setup a package in the package manager mock. Useful for faking installed applications.
1367 *
1368 * @param packageName the name of the package to be setup
1369 * @param userId the user id where the package will be "installed"
1370 * @param appId the application ID to be given to the package
1371 * @param flags flags to set in the ApplicationInfo for this package
1372 * @return the UID of the package as known by the mock package manager
1373 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001374 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1375 int flags) throws Exception {
1376 final int uid = UserHandle.getUid(userId, appId);
1377 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001378 final PackageInfo pi = new PackageInfo();
1379 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001380 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001381 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001382 eq(packageName),
1383 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001384 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001385 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001386 eq(packageName),
1387 anyInt(),
1388 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001389 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001390 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001391 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001392 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001393 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001394 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001395 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001396 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001397 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001398 return uid;
1399 }
1400
Robin Lee7f5c91c2017-02-08 21:27:02 +00001401 public void testCertificateDisclosure() throws Exception {
1402 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1403 final UserHandle user = UserHandle.of(userId);
1404
1405 mContext.applicationInfo = new ApplicationInfo();
1406 mContext.callerPermissions.add(permission.MANAGE_USERS);
1407 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001408 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001409 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1410
Robin Leeabaa0692017-02-20 20:54:22 +00001411 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1412 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001413
1414 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1415 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1416
1417 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001418 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001419 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001420 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001421 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001422 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001423 .cancelAsUser(anyString(), anyInt(), eq(user));
1424
1425 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001426 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001427 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001428 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1429 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001430 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001431 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001432 .notifyAsUser(anyString(), anyInt(), argThat(
1433 new BaseMatcher<Notification>() {
1434 @Override
1435 public boolean matches(Object item) {
1436 final Notification noti = (Notification) item;
1437 return TEST_STRING.equals(
1438 noti.extras.getString(Notification.EXTRA_TITLE));
1439 }
1440 @Override
1441 public void describeTo(Description description) {
1442 description.appendText(
1443 "Notification{title=\"" + TEST_STRING + "\"}");
1444 }
1445 }), eq(user));
1446 }
1447
Edman Anjosf9946772016-11-28 16:35:15 +01001448 /**
1449 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1450 * privileges can acually be exercised by a delegate are not covered here.
1451 */
1452 public void testDelegation() throws Exception {
1453 setAsProfileOwner(admin1);
1454
1455 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1456
1457 // Given two packages
1458 final String CERT_DELEGATE = "com.delegate.certs";
1459 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1460 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1461 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1462 20989);
1463
1464 // On delegation
1465 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1466 mContext.packageName = admin1.getPackageName();
1467 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1468 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1469
1470 // DPMS correctly stores and retrieves the delegates
1471 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1472 assertEquals(2, policy.mDelegationMap.size());
1473 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1474 DELEGATION_CERT_INSTALL);
1475 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1476 DELEGATION_CERT_INSTALL);
1477 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1478 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1479 DELEGATION_APP_RESTRICTIONS);
1480 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1481 DELEGATION_APP_RESTRICTIONS);
1482 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1483
1484 // On calling install certificate APIs from an unauthorized process
1485 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1486 mContext.packageName = RESTRICTIONS_DELEGATE;
1487
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001488 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1489 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001490
1491 // On calling install certificate APIs from an authorized process
1492 mContext.binder.callingUid = CERT_DELEGATE_UID;
1493 mContext.packageName = CERT_DELEGATE;
1494
1495 // DPMS executes without a SecurityException
1496 try {
1497 dpm.installCaCert(null, null);
1498 } catch (SecurityException unexpected) {
1499 fail("Threw SecurityException on authorized access");
1500 } catch (NullPointerException expected) {
1501 }
1502
1503 // On removing a delegate
1504 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1505 mContext.packageName = admin1.getPackageName();
1506 dpm.setCertInstallerPackage(admin1, null);
1507
1508 // DPMS does not allow access to ex-delegate
1509 mContext.binder.callingUid = CERT_DELEGATE_UID;
1510 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001511 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1512 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001513
1514 // But still allows access to other existing delegates
1515 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1516 mContext.packageName = RESTRICTIONS_DELEGATE;
1517 try {
1518 dpm.getApplicationRestrictions(null, "pkg");
1519 } catch (SecurityException expected) {
1520 fail("Threw SecurityException on authorized access");
1521 }
1522 }
1523
Esteban Talaverabf60f722015-12-10 16:26:44 +00001524 public void testApplicationRestrictionsManagingApp() throws Exception {
1525 setAsProfileOwner(admin1);
1526
Rubin Xued1928a2016-02-11 17:23:06 +00001527 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001528 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001529 final String nonDelegateExceptionMessageRegex =
1530 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001531 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001532 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1533 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001534
Esteban Talaverabf60f722015-12-10 16:26:44 +00001535 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1536 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001537 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1538 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001539 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001540 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001541 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001542 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1543 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001544
1545 // Check via the profile owner that no restrictions were set.
1546 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001547 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001548 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1549
Rubin Xued1928a2016-02-11 17:23:06 +00001550 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001551 assertExpectException(PackageManager.NameNotFoundException.class,
1552 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1553 () -> dpm.setApplicationRestrictionsManagingPackage(
1554 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001555
Esteban Talaverabf60f722015-12-10 16:26:44 +00001556 // Let appRestrictionsManagerPackage manage app restrictions
1557 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1558 assertEquals(appRestrictionsManagerPackage,
1559 dpm.getApplicationRestrictionsManagingPackage(admin1));
1560
1561 // Now that package should be able to set and retrieve app restrictions.
1562 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001563 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001564 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1565 dpm.setApplicationRestrictions(null, "pkg1", rest);
1566 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1567 assertEquals(1, returned.size(), 1);
1568 assertEquals("Foo1", returned.get("KEY_STRING"));
1569
1570 // The same app running on a separate user shouldn't be able to manage app restrictions.
1571 mContext.binder.callingUid = UserHandle.getUid(
1572 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1573 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001574 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1575 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001576
1577 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1578 // too.
1579 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001580 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001581 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1582 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1583 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1584
1585 // Removing the ability for the package to manage app restrictions.
1586 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1587 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1588 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001589 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001590 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001591 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1592 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001593 }
1594
Makoto Onukia4f11972015-10-01 13:19:58 -07001595 public void testSetUserRestriction_asDo() throws Exception {
1596 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001597 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001598 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1599 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1600
1601 // First, set DO.
1602
1603 // Call from a process on the system user.
1604 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1605
1606 // Make sure admin1 is installed on system user.
1607 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001608
1609 // Call.
1610 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001611 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001612 UserHandle.USER_SYSTEM));
1613
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001614 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001615 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001616 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001617 DpmTestUtils.assertRestrictions(
1618 DpmTestUtils.newRestrictions(defaultRestrictions),
1619 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1620 );
1621 DpmTestUtils.assertRestrictions(
1622 DpmTestUtils.newRestrictions(defaultRestrictions),
1623 dpm.getUserRestrictions(admin1)
1624 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001625 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001626 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001627 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001628 eq(true) /* isDeviceOwner */,
1629 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001630 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001631 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001632
1633 for (String restriction : defaultRestrictions) {
1634 dpm.clearUserRestriction(admin1, restriction);
1635 }
1636
Esteban Talavera548a04b2016-12-20 15:22:30 +00001637 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001638 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001639
1640 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001641 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001642 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001643 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1644 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001645 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001646
Makoto Onukia4f11972015-10-01 13:19:58 -07001647 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001648 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001649 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001650 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1651 UserManager.DISALLOW_ADD_USER),
1652 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001653 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001654
Makoto Onuki068c54a2015-10-13 14:34:03 -07001655 DpmTestUtils.assertRestrictions(
1656 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001657 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001658 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1659 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001660 DpmTestUtils.assertRestrictions(
1661 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001662 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001663 dpm.getUserRestrictions(admin1)
1664 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001665
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001666 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001667 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001668 eq(UserHandle.USER_SYSTEM),
1669 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001670 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001671 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001672
Makoto Onuki068c54a2015-10-13 14:34:03 -07001673 DpmTestUtils.assertRestrictions(
1674 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1675 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1676 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001677 DpmTestUtils.assertRestrictions(
1678 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1679 dpm.getUserRestrictions(admin1)
1680 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001681
1682 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001683 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001684 eq(UserHandle.USER_SYSTEM),
1685 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001686 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001687 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001688
Esteban Talavera548a04b2016-12-20 15:22:30 +00001689 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001690
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001691 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1692 // DO sets them, the scope is global.
1693 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001694 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001695 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001696 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001697 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001699 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1700 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001701 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702
1703 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1704 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001705 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001706
1707 // More tests.
1708 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001709 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001710 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001711 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1712 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001713 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001714
1715 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001716 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001717 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001718 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001719 UserManager.DISALLOW_ADD_USER),
1720 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001721 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001722
1723 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001724 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001725 eq(UserHandle.USER_SYSTEM),
1726 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 UserManager.DISALLOW_ADD_USER),
1729 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001730 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001731 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001732
Eric Sandnessca5969d2018-08-10 13:28:46 +01001733 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1734 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1735 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001736
Eric Sandnessca5969d2018-08-10 13:28:46 +01001737 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1738 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001739
Eric Sandnessca5969d2018-08-10 13:28:46 +01001740 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1741 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1742 () -> dpm.setCameraDisabled(admin1, true));
1743 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1744
1745 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1746 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1747 () -> dpm.setKeyguardDisabledFeatures(admin1,
1748 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1749 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1750
1751 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1752 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1753 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1754 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1755
1756 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1757 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1758 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1759 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001760 }
1761
1762 public void testSetUserRestriction_asPo() {
1763 setAsProfileOwner(admin1);
1764
Makoto Onuki068c54a2015-10-13 14:34:03 -07001765 DpmTestUtils.assertRestrictions(
1766 DpmTestUtils.newRestrictions(),
1767 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1768 .ensureUserRestrictions()
1769 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001770
1771 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001773 eq(DpmMockContext.CALLER_USER_HANDLE),
1774 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001775 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001776 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001777
Makoto Onukia4f11972015-10-01 13:19:58 -07001778 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001779 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001780 eq(DpmMockContext.CALLER_USER_HANDLE),
1781 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1782 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001783 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001784 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001785
Makoto Onuki068c54a2015-10-13 14:34:03 -07001786 DpmTestUtils.assertRestrictions(
1787 DpmTestUtils.newRestrictions(
1788 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1789 UserManager.DISALLOW_OUTGOING_CALLS
1790 ),
1791 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1792 .ensureUserRestrictions()
1793 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001794 DpmTestUtils.assertRestrictions(
1795 DpmTestUtils.newRestrictions(
1796 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1797 UserManager.DISALLOW_OUTGOING_CALLS
1798 ),
1799 dpm.getUserRestrictions(admin1)
1800 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001801
1802 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001803 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001804 eq(DpmMockContext.CALLER_USER_HANDLE),
1805 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001806 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001807 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001808
1809 DpmTestUtils.assertRestrictions(
1810 DpmTestUtils.newRestrictions(
1811 UserManager.DISALLOW_OUTGOING_CALLS
1812 ),
1813 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1814 .ensureUserRestrictions()
1815 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001816 DpmTestUtils.assertRestrictions(
1817 DpmTestUtils.newRestrictions(
1818 UserManager.DISALLOW_OUTGOING_CALLS
1819 ),
1820 dpm.getUserRestrictions(admin1)
1821 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001822
1823 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001824 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001825 eq(DpmMockContext.CALLER_USER_HANDLE),
1826 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001827 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001828 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001829
Makoto Onuki068c54a2015-10-13 14:34:03 -07001830 DpmTestUtils.assertRestrictions(
1831 DpmTestUtils.newRestrictions(),
1832 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1833 .ensureUserRestrictions()
1834 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001835 DpmTestUtils.assertRestrictions(
1836 DpmTestUtils.newRestrictions(),
1837 dpm.getUserRestrictions(admin1)
1838 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001839
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001840 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1841 // though when DO sets them they'll be applied globally.
1842 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001843 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001844 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001845 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001846 eq(DpmMockContext.CALLER_USER_HANDLE),
1847 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1848 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001849 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001850 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001851
1852 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001853 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001854 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001855 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001856 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001857 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001858 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001859
Makoto Onukia4f11972015-10-01 13:19:58 -07001860 // TODO Make sure restrictions are written to the file.
1861 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001862
Esteban Talavera548a04b2016-12-20 15:22:30 +00001863
1864 public void testDefaultEnabledUserRestrictions() throws Exception {
1865 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1866 mContext.callerPermissions.add(permission.MANAGE_USERS);
1867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1868 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1869
1870 // First, set DO.
1871
1872 // Call from a process on the system user.
1873 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1874
1875 // Make sure admin1 is installed on system user.
1876 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1877
1878 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1879 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1880 UserHandle.USER_SYSTEM));
1881
1882 // Check that the user restrictions that are enabled by default are set. Then unset them.
1883 String[] defaultRestrictions = UserRestrictionsUtils
1884 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1885 assertTrue(defaultRestrictions.length > 0);
1886 DpmTestUtils.assertRestrictions(
1887 DpmTestUtils.newRestrictions(defaultRestrictions),
1888 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1889 );
1890 DpmTestUtils.assertRestrictions(
1891 DpmTestUtils.newRestrictions(defaultRestrictions),
1892 dpm.getUserRestrictions(admin1)
1893 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001894 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001895 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001896 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001897 eq(true) /* isDeviceOwner */,
1898 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001899 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001900 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001901
1902 for (String restriction : defaultRestrictions) {
1903 dpm.clearUserRestriction(admin1, restriction);
1904 }
1905
1906 assertNoDeviceOwnerRestrictions();
1907
1908 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001909 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001910 initializeDpms();
1911 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1912 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1913
1914 assertNoDeviceOwnerRestrictions();
1915
1916 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1917 // is set as it wasn't enabled during setDeviceOwner.
1918 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1919 assertFalse(UserRestrictionsUtils
1920 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1921 UserRestrictionsUtils
1922 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1923 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001924 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001925 initializeDpms();
1926 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1927 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1928
1929 DpmTestUtils.assertRestrictions(
1930 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1931 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1932 );
1933 DpmTestUtils.assertRestrictions(
1934 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1935 dpm.getUserRestrictions(admin1)
1936 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001937 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001938 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001939 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001940 eq(true) /* isDeviceOwner */,
1941 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001942 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001943 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001944
1945 // Remove the restriction.
1946 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1947
1948 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1949 initializeDpms();
1950 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1951 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1952 assertNoDeviceOwnerRestrictions();
1953 } finally {
1954 UserRestrictionsUtils
1955 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1956 }
1957 }
1958
1959 private void assertNoDeviceOwnerRestrictions() {
1960 DpmTestUtils.assertRestrictions(
1961 DpmTestUtils.newRestrictions(),
1962 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1963 );
1964 DpmTestUtils.assertRestrictions(
1965 DpmTestUtils.newRestrictions(),
1966 dpm.getUserRestrictions(admin1)
1967 );
1968 }
1969
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001970 public void testGetMacAddress() throws Exception {
1971 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1972 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1973 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1974
1975 // In this test, change the caller user to "system".
1976 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1977
1978 // Make sure admin1 is installed on system user.
1979 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1980
1981 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001982 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
1983 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001984
1985 // DO needs to be an DA.
1986 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1987 assertTrue(dpm.isAdminActive(admin1));
1988
1989 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001990 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1991 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001992
1993 // Test 3. Caller has PO, but not DO.
1994 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001995 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
1996 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001997
1998 // Remove PO.
1999 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002000 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002001 // Test 4, Caller is DO now.
2002 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2003
xshu425b9a62018-12-13 14:18:18 -08002004 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002005 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002006
xshu425b9a62018-12-13 14:18:18 -08002007 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2008 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002009 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002010
2011 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002012 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2013 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002014 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002015 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002016
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002017 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002018 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2019 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2020
2021 // In this test, change the caller user to "system".
2022 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2023
2024 // Make sure admin1 is installed on system user.
2025 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2026
2027 // Set admin1 as DA.
2028 dpm.setActiveAdmin(admin1, false);
2029 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002030 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2031 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002032
2033 // Set admin1 as PO.
2034 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002035 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2036 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002037
2038 // Remove PO and add DO.
2039 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002040 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002041 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2042
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002043 // admin1 is DO.
2044 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002045 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002046 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002047 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2048 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002049
2050 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002051 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002052 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002053 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2054 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002055
2056 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002057 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002058 dpm.reboot(admin1);
2059 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002060
2061 public void testSetGetSupportText() {
2062 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2063 dpm.setActiveAdmin(admin1, true);
2064 dpm.setActiveAdmin(admin2, true);
2065 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2066
2067 // Null default support messages.
2068 {
2069 assertNull(dpm.getLongSupportMessage(admin1));
2070 assertNull(dpm.getShortSupportMessage(admin1));
2071 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2072 assertNull(dpm.getShortSupportMessageForUser(admin1,
2073 DpmMockContext.CALLER_USER_HANDLE));
2074 assertNull(dpm.getLongSupportMessageForUser(admin1,
2075 DpmMockContext.CALLER_USER_HANDLE));
2076 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2077 }
2078
2079 // Only system can call the per user versions.
2080 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002081 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2082 () -> dpm.getShortSupportMessageForUser(admin1,
2083 DpmMockContext.CALLER_USER_HANDLE));
2084 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2085 () -> dpm.getLongSupportMessageForUser(admin1,
2086 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002087 }
2088
2089 // Can't set message for admin in another uid.
2090 {
2091 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002092 assertExpectException(SecurityException.class,
2093 /* messageRegex= */ "is not owned by uid",
2094 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002095 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2096 }
2097
2098 // Set/Get short returns what it sets and other admins text isn't changed.
2099 {
2100 final String supportText = "Some text to test with.";
2101 dpm.setShortSupportMessage(admin1, supportText);
2102 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2103 assertNull(dpm.getLongSupportMessage(admin1));
2104 assertNull(dpm.getShortSupportMessage(admin2));
2105
2106 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2107 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2108 DpmMockContext.CALLER_USER_HANDLE));
2109 assertNull(dpm.getShortSupportMessageForUser(admin2,
2110 DpmMockContext.CALLER_USER_HANDLE));
2111 assertNull(dpm.getLongSupportMessageForUser(admin1,
2112 DpmMockContext.CALLER_USER_HANDLE));
2113 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2114
2115 dpm.setShortSupportMessage(admin1, null);
2116 assertNull(dpm.getShortSupportMessage(admin1));
2117 }
2118
2119 // Set/Get long returns what it sets and other admins text isn't changed.
2120 {
2121 final String supportText = "Some text to test with.\nWith more text.";
2122 dpm.setLongSupportMessage(admin1, supportText);
2123 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2124 assertNull(dpm.getShortSupportMessage(admin1));
2125 assertNull(dpm.getLongSupportMessage(admin2));
2126
2127 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2128 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2129 DpmMockContext.CALLER_USER_HANDLE));
2130 assertNull(dpm.getLongSupportMessageForUser(admin2,
2131 DpmMockContext.CALLER_USER_HANDLE));
2132 assertNull(dpm.getShortSupportMessageForUser(admin1,
2133 DpmMockContext.CALLER_USER_HANDLE));
2134 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2135
2136 dpm.setLongSupportMessage(admin1, null);
2137 assertNull(dpm.getLongSupportMessage(admin1));
2138 }
2139 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002140
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002141 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002142 setAsProfileOwner(admin1);
2143
2144 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002145 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002146
2147 // Setup
2148 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2149 final String package1 = "com.example.one";
2150 final String package2 = "com.example.two";
2151 pkgsToRestrict.add(package1);
2152 pkgsToRestrict.add(package2);
2153 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2154 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002155 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002156
2157 // Verify
2158 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002159 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002160 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2161 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2162 eq(DpmMockContext.CALLER_USER_HANDLE));
2163
2164 // Setup
2165 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002166 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002167
2168 // Verify
2169 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002170 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002171 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2172 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2173 eq(DpmMockContext.CALLER_USER_HANDLE));
2174 }
2175
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002176 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002177 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2178 dpm.setActiveAdmin(admin1, true);
2179 assertTrue(dpm.isAdminActive(admin1));
2180 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2181
2182 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002183 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002184 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002185 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002186 }
2187
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002188 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002189 setAsProfileOwner(admin1);
2190
2191 // Setup
2192 final ArrayList<String> emptyList = new ArrayList<>();
2193 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2194 final String package1 = "com.example.one";
2195 final String package2 = "com.example.two";
2196 final String package3 = "com.example.three";
2197 pkgsToRestrict.add(package1);
2198 pkgsToRestrict.add(package2);
2199 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2200 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002201 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002202
2203 // Verify
2204 assertEquals(emptyList, excludedPkgs);
2205 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2206 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002207 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002208 DpmMockContext.CALLER_USER_HANDLE));
2209 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002210 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002211 DpmMockContext.CALLER_USER_HANDLE));
2212 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002213 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002214 DpmMockContext.CALLER_USER_HANDLE));
2215 }
2216
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002217 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002218 setAsProfileOwner(admin1);
2219 assertExpectException(SecurityException.class,
2220 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002221 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002222 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2223 dpm.clearProfileOwner(admin1);
2224
2225 setDeviceOwner();
2226 assertExpectException(SecurityException.class,
2227 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002228 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002229 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2230 clearDeviceOwner();
2231 }
2232
phweiss73145f42017-01-17 19:06:38 +01002233 public void testCreateAdminSupportIntent() throws Exception {
2234 // Setup device owner.
2235 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2236 setupDeviceOwner();
2237
2238 // Nonexisting permission returns null
2239 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2240 assertNull(intent);
2241
2242 // Existing permission that is not set returns null
2243 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2244 assertNull(intent);
2245
2246 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002247 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002248 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2249 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2250 .thenReturn(true);
2251 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2252 assertNull(intent);
2253
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002254 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2255 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2256 new UserManager.EnforcingUser(
2257 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2258 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002259 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002260 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002261 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2262 assertNotNull(intent);
2263 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2264 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2265 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002266 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002267 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2268 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2269
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002270 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2271 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002272
2273 // Camera is not disabled
2274 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2275 assertNull(intent);
2276
2277 // Camera is disabled
2278 dpm.setCameraDisabled(admin1, true);
2279 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2280 assertNotNull(intent);
2281 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2282 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2283
2284 // Screen capture is not disabled
2285 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2286 assertNull(intent);
2287
2288 // Screen capture is disabled
2289 dpm.setScreenCaptureDisabled(admin1, true);
2290 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2291 assertNotNull(intent);
2292 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2293 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2294
2295 // Same checks for different user
2296 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2297 // Camera should be disabled by device owner
2298 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2299 assertNotNull(intent);
2300 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2301 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2302 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2303 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2304 // ScreenCapture should not be disabled by device owner
2305 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2306 assertNull(intent);
2307 }
2308
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002309 /**
2310 * Test for:
2311 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002312 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002313 * {@link DevicePolicyManager#isAffiliatedUser}
2314 */
2315 public void testUserAffiliation() throws Exception {
2316 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2317 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2318 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2319
2320 // Check that the system user is unaffiliated.
2321 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2322 assertFalse(dpm.isAffiliatedUser());
2323
2324 // Set a device owner on the system user. Check that the system user becomes affiliated.
2325 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2326 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2327 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2328 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002329 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002330
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002331 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002332 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2333 setAsProfileOwner(admin2);
2334 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002335 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002336
2337 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2338 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002339 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002340 userAffiliationIds.add("red");
2341 userAffiliationIds.add("green");
2342 userAffiliationIds.add("blue");
2343 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002344 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002345 assertFalse(dpm.isAffiliatedUser());
2346
2347 // Have the device owner specify a set of affiliation ids that do not intersect with those
2348 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002349 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002350 deviceAffiliationIds.add("cyan");
2351 deviceAffiliationIds.add("yellow");
2352 deviceAffiliationIds.add("magenta");
2353 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2354 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002355 MoreAsserts.assertContentsInAnyOrder(
2356 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002357 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2358 assertFalse(dpm.isAffiliatedUser());
2359
2360 // Have the profile owner specify a set of affiliation ids that intersect with those
2361 // specified by the device owner. Check that the test user becomes affiliated.
2362 userAffiliationIds.add("yellow");
2363 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002364 MoreAsserts.assertContentsInAnyOrder(
2365 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002366 assertTrue(dpm.isAffiliatedUser());
2367
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002368 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002369 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002370 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002371 assertFalse(dpm.isAffiliatedUser());
2372
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002373 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2374 dpm.setAffiliationIds(admin2, userAffiliationIds);
2375 assertTrue(dpm.isAffiliatedUser());
2376 dpm.clearProfileOwner(admin2);
2377 assertFalse(dpm.isAffiliatedUser());
2378
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002379 // Check that the system user remains affiliated.
2380 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2381 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002382
2383 // Clear the device owner - the user becomes unaffiliated.
2384 clearDeviceOwner();
2385 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002386 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002387
2388 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002389 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002390 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2391 }
2392
2393 public void testSetUserProvisioningState_permission() throws Exception {
2394 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002395
2396 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2397 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2398 }
2399
2400 public void testSetUserProvisioningState_unprivileged() throws Exception {
2401 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002402 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2403 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2404 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002405 }
2406
2407 public void testSetUserProvisioningState_noManagement() {
2408 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002409 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002410 assertExpectException(IllegalStateException.class,
2411 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2412 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2413 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002414 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2415 }
2416
2417 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2418 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2419 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002420
2421 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2422 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2423 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2424 }
2425
2426 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2427 throws Exception {
2428 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2429 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002430
2431 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2432 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2433 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2434 }
2435
2436 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2437 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2438 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002439
2440 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2441 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2442 }
2443
2444 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2445 throws Exception {
2446 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002447
2448 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2449 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2450 DevicePolicyManager.STATE_USER_UNMANAGED);
2451 }
2452
2453 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2454 throws Exception {
2455 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002456
2457 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2458 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2459 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2460 }
2461
2462 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2463 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002464
2465 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2466 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2467 }
2468
2469 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2470 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002471
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002472 assertExpectException(IllegalStateException.class,
2473 /* messageRegex= */ "Cannot move to user provisioning state",
2474 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2475 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2476 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002477 }
2478
2479 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2480 throws Exception {
2481 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002482
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002483 assertExpectException(IllegalStateException.class,
2484 /* messageRegex= */ "Cannot move to user provisioning state",
2485 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2486 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2487 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002488 }
2489
2490 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002491 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2492 mContext.callerPermissions.add(permission.MANAGE_USERS);
2493
Alan Treadwayafad8782016-01-19 15:15:08 +00002494 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2495 for (int state : states) {
2496 dpm.setUserProvisioningState(state, userId);
2497 assertEquals(state, dpm.getUserProvisioningState());
2498 }
2499 }
2500
2501 private void setupProfileOwner() throws Exception {
2502 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2503
2504 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2505 dpm.setActiveAdmin(admin1, false);
2506 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2507
2508 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2509 }
2510
2511 private void setupDeviceOwner() throws Exception {
2512 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2513
2514 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2515 dpm.setActiveAdmin(admin1, false);
2516 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2517
2518 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2519 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002520
2521 public void testSetMaximumTimeToLock() {
2522 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2523
2524 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2525 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2526
Pavel Grafov75c0a892017-05-18 17:28:27 +01002527 reset(getServices().powerManagerInternal);
2528 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002529
2530 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002531 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2532 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002533 reset(getServices().powerManagerInternal);
2534 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002535
2536 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002537 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2538 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002539 reset(getServices().powerManagerInternal);
2540 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002541
2542 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002543 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2544 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002545 reset(getServices().powerManagerInternal);
2546 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002547
2548 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002549 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2550 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002551 reset(getServices().powerManagerInternal);
2552 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002553
2554 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002555 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2556 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002557 reset(getServices().powerManagerInternal);
2558 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002559
2560 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002561 reset(getServices().powerManagerInternal);
2562 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002563
Pavel Grafov28939982017-10-03 15:11:52 +01002564 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2565 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2566 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002567 reset(getServices().powerManagerInternal);
2568 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002569
2570 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002571 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2572 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002573 reset(getServices().powerManagerInternal);
2574 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002575
Pavel Grafov28939982017-10-03 15:11:52 +01002576 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002577 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002578 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2579 verifyStayOnWhilePluggedCleared(false);
2580 }
2581
2582 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2583 // uses separate challenge.
2584 public void testSetMaximumTimeToLockProfile() throws Exception {
2585 final int PROFILE_USER = 15;
2586 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2587 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2588 mContext.binder.callingUid = PROFILE_ADMIN;
2589 final DevicePolicyManagerInternal dpmi =
2590 LocalServices.getService(DevicePolicyManagerInternal.class);
2591
2592 dpm.setMaximumTimeToLock(admin1, 0);
2593
2594 reset(getServices().powerManagerInternal);
2595 reset(getServices().settings);
2596
2597 // First add timeout for the profile.
2598 dpm.setMaximumTimeToLock(admin1, 10);
2599 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2600
2601 reset(getServices().powerManagerInternal);
2602 reset(getServices().settings);
2603
2604 // Add separate challenge
2605 when(getServices().lockPatternUtils
2606 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2607 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2608
2609 verifyScreenTimeoutCall(10L, PROFILE_USER);
2610 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2611
2612 reset(getServices().powerManagerInternal);
2613 reset(getServices().settings);
2614
2615 // Remove the timeout.
2616 dpm.setMaximumTimeToLock(admin1, 0);
2617 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2618 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2619
2620 reset(getServices().powerManagerInternal);
2621 reset(getServices().settings);
2622
2623 // Add it back.
2624 dpm.setMaximumTimeToLock(admin1, 10);
2625 verifyScreenTimeoutCall(10L, PROFILE_USER);
2626 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2627
2628 reset(getServices().powerManagerInternal);
2629 reset(getServices().settings);
2630
2631 // Remove separate challenge.
2632 reset(getServices().lockPatternUtils);
2633 when(getServices().lockPatternUtils
2634 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2635 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002636 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002637
2638 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2639 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2640
2641 reset(getServices().powerManagerInternal);
2642 reset(getServices().settings);
2643
2644 // Remove the timeout.
2645 dpm.setMaximumTimeToLock(admin1, 0);
2646 verifyScreenTimeoutCall(null, PROFILE_USER);
2647 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002648 }
2649
Michal Karpinski943aabd2016-10-06 11:09:25 +01002650 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2651 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2652 setupDeviceOwner();
2653 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2654
Michal Karpinskid084ca52017-01-18 15:54:18 +00002655 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2656 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2657 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2658 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2659 - ONE_MINUTE;
2660
2661 // verify that the minimum timeout cannot be modified on user builds (system property is
2662 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002663 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002664
2665 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2666 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2667 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2668
Pavel Grafov75c0a892017-05-18 17:28:27 +01002669 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002670
2671 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002672 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002673
Michal Karpinskid084ca52017-01-18 15:54:18 +00002674 // reset to default (0 means the admin is not participating, so default should be returned)
2675 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002676
2677 // aggregation should be the default if unset by any admin
2678 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2679 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2680
2681 // admin not participating by default
2682 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2683
2684 //clamping from the top
2685 dpm.setRequiredStrongAuthTimeout(admin1,
2686 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2687 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2688 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2689 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2690 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2691
Michal Karpinskid084ca52017-01-18 15:54:18 +00002692 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002693 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2694 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2695 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2696 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2697
2698 // clamping from the bottom
2699 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2700 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2701 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2702
Michal Karpinskid084ca52017-01-18 15:54:18 +00002703 // values within range
2704 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2705 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2706 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2707
2708 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2709 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2710 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002711
2712 // reset to default
2713 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2714 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2715 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2716 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2717
2718 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002719 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2720 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002721 }
2722
Pavel Grafov28939982017-10-03 15:11:52 +01002723 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002724 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002725 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002726 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002727 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002728 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002729 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002730 }
Pavel Grafov28939982017-10-03 15:11:52 +01002731 }
2732
2733 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002734 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2735 // UnfinishedVerificationException.
2736 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002737
Esteban Talavera01576862016-12-15 11:16:44 +00002738 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002739 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002740 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002741 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002742 .thenReturn(false);
2743 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002744 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2745 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002746 .thenReturn(true);
2747 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2748
2749 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002750 }
Victor Chang3e794af2016-03-04 13:48:17 +00002751
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002752 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2753 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002754 mContext.packageName = admin1.getPackageName();
2755 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002756 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2757 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2758 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2759 false);
2760 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2761 }
2762
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002763 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2764 setup_DeviceAdminFeatureOff();
2765 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2766 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2767 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2768 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2769 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2770 assertCheckProvisioningPreCondition(
2771 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2772 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2773 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2774 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2775 }
2776
Esteban Talavera01576862016-12-15 11:16:44 +00002777 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002778 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002779 .thenReturn(false);
2780 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002781 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2782 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002783 .thenReturn(true);
2784 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2785
2786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002787 }
Victor Chang3e794af2016-03-04 13:48:17 +00002788
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002789 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2790 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002791 mContext.packageName = admin1.getPackageName();
2792 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002793 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2794 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2795 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2796 false);
2797 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2798
2799 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002800 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002801 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2802 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2803 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2804 true);
2805 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2806 }
2807
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002808 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2809 setup_ManagedProfileFeatureOff();
2810 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2812 DevicePolicyManager.CODE_OK);
2813 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2814 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2815 assertCheckProvisioningPreCondition(
2816 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2817 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2818 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2819 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2820
2821 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002822 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002823 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2824 DevicePolicyManager.CODE_OK);
2825 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2826 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2827 assertCheckProvisioningPreCondition(
2828 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2829 DevicePolicyManager.CODE_OK);
2830 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2831 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2832 }
2833
Esteban Talavera01576862016-12-15 11:16:44 +00002834 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002835 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002836 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002837 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2838 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002839 .thenReturn(true);
2840 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2841
2842 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002843 }
Victor Chang3e794af2016-03-04 13:48:17 +00002844
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002845 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2846 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002847 mContext.packageName = admin1.getPackageName();
2848 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002849 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2850 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2851 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2852 false /* because of non-split user */);
2853 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2854 false /* because of non-split user */);
2855 }
2856
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002857 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002858 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002859 setup_nonSplitUser_firstBoot_primaryUser();
2860 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2861 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2862 DevicePolicyManager.CODE_OK);
2863 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2864 DevicePolicyManager.CODE_OK);
2865 assertCheckProvisioningPreCondition(
2866 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2867 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2868 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2869 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2870 }
2871
Esteban Talavera01576862016-12-15 11:16:44 +00002872 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002873 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002874 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002875 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2876 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002877 .thenReturn(true);
2878 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2879
2880 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002881 }
Victor Chang3e794af2016-03-04 13:48:17 +00002882
Nicolas Prevot45d29072017-01-18 16:11:19 +00002883 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2884 setDeviceOwner();
2885 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2886 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2887 }
2888
2889 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2890 setup_nonSplitUser_withDo_primaryUser();
2891 final int MANAGED_PROFILE_USER_ID = 18;
2892 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2893 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002894 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002895 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002896 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002897 true)).thenReturn(true);
2898 }
2899
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002900 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2901 throws Exception {
2902 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002903 mContext.packageName = admin1.getPackageName();
2904 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002905 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2906 false/* because of completed device setup */);
2907 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2909 false/* because of non-split user */);
2910 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2911 false/* because of non-split user */);
2912 }
2913
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2915 throws Exception {
2916 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2917 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2918 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2919 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2920 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2921 DevicePolicyManager.CODE_OK);
2922 assertCheckProvisioningPreCondition(
2923 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2924 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2925 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2926 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2927 }
2928
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2930 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002931 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002932 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2933
2934 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2935 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002936 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002937
2938 // COMP mode is allowed.
2939 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2940 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002941 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002942
Nicolas Prevot45d29072017-01-18 16:11:19 +00002943 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002944 assertCheckProvisioningPreCondition(
2945 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002946 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002947 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002948 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2949 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2950 }
Esteban Talavera01576862016-12-15 11:16:44 +00002951
Nicolas Prevot45d29072017-01-18 16:11:19 +00002952 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2953 setup_nonSplitUser_withDo_primaryUser();
2954 mContext.packageName = admin1.getPackageName();
2955 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2956 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2957 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002958 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002959 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2960 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2961 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002962 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002963 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2964 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2965 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2966 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2967 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002968 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002969 assertCheckProvisioningPreCondition(
2970 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002971 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002972 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002973 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2974 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2975 }
Esteban Talavera01576862016-12-15 11:16:44 +00002976
Nicolas Prevot45d29072017-01-18 16:11:19 +00002977 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2978 throws Exception {
2979 setup_nonSplitUser_withDo_primaryUser();
2980 mContext.packageName = admin1.getPackageName();
2981 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002982 // The DO should not be allowed to initiate provisioning if the restriction is set by
2983 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002984 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00002985 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2986 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2987 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002988 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002989 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2990 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2991 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2992 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2993 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002994 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2995
2996 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002997 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002998 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002999 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3001 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3002 }
3003
3004 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3005 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3006 mContext.packageName = admin1.getPackageName();
3007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3008
3009 // We can delete the managed profile to create a new one, so provisioning is allowed.
3010 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3011 DevicePolicyManager.CODE_OK);
3012 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3013 assertCheckProvisioningPreCondition(
3014 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3015 DpmMockContext.ANOTHER_PACKAGE_NAME,
3016 DevicePolicyManager.CODE_OK);
3017 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3018 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3019 }
3020
3021 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3022 throws Exception {
3023 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3024 mContext.packageName = admin1.getPackageName();
3025 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003026 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003027 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3028 eq(UserHandle.SYSTEM)))
3029 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003030 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003031 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3032 eq(UserHandle.SYSTEM)))
3033 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003034
3035 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003036 assertCheckProvisioningPreCondition(
3037 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3038 DpmMockContext.ANOTHER_PACKAGE_NAME,
3039 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3040 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3041 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003042
3043 // But the device owner can still do it because it has set the restriction itself.
3044 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3045 DevicePolicyManager.CODE_OK);
3046 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003047 }
3048
3049 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003050 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003051 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003052 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3053 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003054 .thenReturn(false);
3055 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3056
3057 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003058 }
Victor Chang3e794af2016-03-04 13:48:17 +00003059
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003060 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3061 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003062 mContext.packageName = admin1.getPackageName();
3063 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003064 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3065 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3066 false /* because canAddMoreManagedProfiles returns false */);
3067 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3068 true);
3069 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3070 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003071 }
3072
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003073 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3074 throws Exception {
3075 setup_splitUser_firstBoot_systemUser();
3076 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3077 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3078 DevicePolicyManager.CODE_OK);
3079 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003080 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003081 assertCheckProvisioningPreCondition(
3082 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3083 DevicePolicyManager.CODE_OK);
3084 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3085 DevicePolicyManager.CODE_SYSTEM_USER);
3086 }
3087
Esteban Talavera01576862016-12-15 11:16:44 +00003088 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003089 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003090 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003091 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3092 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003093 .thenReturn(false);
3094 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3095
3096 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003097 }
Victor Chang3e794af2016-03-04 13:48:17 +00003098
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003099 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3100 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003101 mContext.packageName = admin1.getPackageName();
3102 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003103 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3104 true/* it's undefined behavior. Can be changed into false in the future */);
3105 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3106 false /* because canAddMoreManagedProfiles returns false */);
3107 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3108 true/* it's undefined behavior. Can be changed into false in the future */);
3109 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3110 false/* because calling uid is system user */);
3111 }
3112
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003113 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3114 throws Exception {
3115 setup_splitUser_afterDeviceSetup_systemUser();
3116 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3117 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3118 DevicePolicyManager.CODE_OK);
3119 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003120 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003121 assertCheckProvisioningPreCondition(
3122 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3123 DevicePolicyManager.CODE_OK);
3124 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3125 DevicePolicyManager.CODE_SYSTEM_USER);
3126 }
3127
Esteban Talavera01576862016-12-15 11:16:44 +00003128 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003129 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003130 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003131 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3132 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003133 true)).thenReturn(true);
3134 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3135
3136 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003137 }
Victor Chang3e794af2016-03-04 13:48:17 +00003138
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003139 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3140 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003141 mContext.packageName = admin1.getPackageName();
3142 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003143 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3144 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3145 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3146 true);
3147 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003148 }
3149
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003150 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003151 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003152 setup_splitUser_firstBoot_primaryUser();
3153 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3154 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3155 DevicePolicyManager.CODE_OK);
3156 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3157 DevicePolicyManager.CODE_OK);
3158 assertCheckProvisioningPreCondition(
3159 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3160 DevicePolicyManager.CODE_OK);
3161 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3162 DevicePolicyManager.CODE_OK);
3163 }
3164
Esteban Talavera01576862016-12-15 11:16:44 +00003165 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003166 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003167 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003168 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3169 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003170 true)).thenReturn(true);
3171 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3172
3173 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003174 }
Victor Chang3e794af2016-03-04 13:48:17 +00003175
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003176 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3177 throws Exception {
3178 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003179 mContext.packageName = admin1.getPackageName();
3180 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003181 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3182 true/* it's undefined behavior. Can be changed into false in the future */);
3183 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3184 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3185 true/* it's undefined behavior. Can be changed into false in the future */);
3186 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3187 false/* because user setup completed */);
3188 }
3189
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003190 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003191 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003192 setup_splitUser_afterDeviceSetup_primaryUser();
3193 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3194 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3195 DevicePolicyManager.CODE_OK);
3196 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3197 DevicePolicyManager.CODE_OK);
3198 assertCheckProvisioningPreCondition(
3199 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3200 DevicePolicyManager.CODE_OK);
3201 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3202 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3203 }
3204
Esteban Talavera01576862016-12-15 11:16:44 +00003205 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003206 setDeviceOwner();
3207
Pavel Grafov75c0a892017-05-18 17:28:27 +01003208 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003209 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003210 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3211 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003212 .thenReturn(false);
3213 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3214
3215 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003216 }
Victor Chang3e794af2016-03-04 13:48:17 +00003217
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003218 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3219 throws Exception {
3220 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003221 mContext.packageName = admin1.getPackageName();
3222 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003223 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3224 false /* can't provision managed profile on system user */);
3225 }
3226
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003227 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003228 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003229 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3230 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3231 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3232 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3233 }
3234
3235 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003236 setDeviceOwner();
3237
Pavel Grafov75c0a892017-05-18 17:28:27 +01003238 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003239 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003240 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3241 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003242 true)).thenReturn(true);
3243 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3244
3245 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003246 }
Victor Chang3e794af2016-03-04 13:48:17 +00003247
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003248 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3249 throws Exception {
3250 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003251 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3252 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003253 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3254 }
3255
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003256 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003257 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003258 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3259 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003260
3261 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003262 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3263 DevicePolicyManager.CODE_OK);
3264 }
3265
3266 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003267 setDeviceOwner();
3268
Pavel Grafov75c0a892017-05-18 17:28:27 +01003269 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003270 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003271 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3272 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003273 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3274 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003275 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003276 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003277 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003278 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003279 true)).thenReturn(true);
3280 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3281
3282 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003283 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003284
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003285 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3286 throws Exception {
3287 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003288 mContext.packageName = admin1.getPackageName();
3289 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003290 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3291 }
3292
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003293 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3294 throws Exception {
3295 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3296 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3297 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3298 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3299 }
3300
3301 public void testCheckProvisioningPreCondition_permission() {
3302 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003303 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3304 () -> dpm.checkProvisioningPreCondition(
3305 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003306 }
3307
Victor Chang3577ed22016-08-25 18:49:26 +01003308 public void testForceUpdateUserSetupComplete_permission() {
3309 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003310 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3311 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003312 }
3313
3314 public void testForceUpdateUserSetupComplete_systemUser() {
3315 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3316 // GIVEN calling from user 20
3317 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003318 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3319 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003320 }
3321
3322 public void testForceUpdateUserSetupComplete_userbuild() {
3323 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3324 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3325
3326 final int userId = UserHandle.USER_SYSTEM;
3327 // GIVEN userComplete is false in SettingsProvider
3328 setUserSetupCompleteForUser(false, userId);
3329
3330 // GIVEN userComplete is true in DPM
3331 DevicePolicyManagerService.DevicePolicyData userData =
3332 new DevicePolicyManagerService.DevicePolicyData(userId);
3333 userData.mUserSetupComplete = true;
3334 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3335
3336 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003337 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003338
3339 assertTrue(dpms.hasUserSetupCompleted());
3340
3341 dpm.forceUpdateUserSetupComplete();
3342
3343 // THEN the state in dpms is not changed
3344 assertTrue(dpms.hasUserSetupCompleted());
3345 }
3346
3347 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3348 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3349 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3350
3351 final int userId = UserHandle.USER_SYSTEM;
3352 // GIVEN userComplete is false in SettingsProvider
3353 setUserSetupCompleteForUser(false, userId);
3354
3355 // GIVEN userComplete is true in DPM
3356 DevicePolicyManagerService.DevicePolicyData userData =
3357 new DevicePolicyManagerService.DevicePolicyData(userId);
3358 userData.mUserSetupComplete = true;
3359 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3360
3361 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003362 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003363
3364 assertTrue(dpms.hasUserSetupCompleted());
3365
3366 dpm.forceUpdateUserSetupComplete();
3367
3368 // THEN the state in dpms is not changed
3369 assertFalse(dpms.hasUserSetupCompleted());
3370 }
3371
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003372 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003373 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003374 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003375
3376 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3377 runAsCaller(mAdmin1Context, dpms, dpm -> {
3378 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3379 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003380 }
3381
3382 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3383 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3384 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003385
3386 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3387 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003388 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003389 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3390 .thenReturn(true);
3391
3392 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003393 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003394
3395 // Enabling logging should not change the timestamp.
3396 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003397 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003398 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003399 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003400 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003401 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003402
3403 // Retrieving the logs should update the timestamp.
3404 final long beforeRetrieval = System.currentTimeMillis();
3405 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003406 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003407 final long afterRetrieval = System.currentTimeMillis();
3408 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3409 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3410
3411 // Retrieving the pre-boot logs should update the timestamp.
3412 Thread.sleep(2);
3413 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003414 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003415 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3416
3417 // Checking the timestamp again should not change it.
3418 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003419 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003420
3421 // Retrieving the logs again should update the timestamp.
3422 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003423 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003424 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3425
3426 // Disabling logging should not change the timestamp.
3427 Thread.sleep(2);
3428 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003429 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003430
3431 // Restarting the DPMS should not lose the timestamp.
3432 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003433 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003434
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003435 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3436 mContext.binder.callingUid = 1234567;
3437 mContext.callerPermissions.add(permission.MANAGE_USERS);
3438 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3439 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3440
3441 // System can retrieve the timestamp.
3442 mContext.binder.clearCallingIdentity();
3443 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3444
3445 // Removing the device owner should clear the timestamp.
3446 clearDeviceOwner();
3447 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003448 }
3449
yuemingw0de748d2017-11-15 19:22:27 +00003450 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3451 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3452 setupDeviceOwner();
3453 assertExpectException(SecurityException.class, null, () ->
3454 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3455 }
3456
yuemingwc0281f12018-03-28 15:58:49 +01003457 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003458 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3459 setupDeviceOwner();
3460 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003461 verify(getServices().settings).settingsSystemPutStringForUser(
3462 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3463 }
3464
3465 public void testSetSystemSettingWithPO() throws Exception {
3466 setupProfileOwner();
3467 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3468 verify(getServices().settings).settingsSystemPutStringForUser(
3469 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003470 }
3471
yuemingwe43cdf72017-10-12 16:52:11 +01003472 public void testSetTime() throws Exception {
3473 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3474 setupDeviceOwner();
3475 dpm.setTime(admin1, 0);
3476 verify(getServices().alarmManager).setTime(0);
3477 }
3478
3479 public void testSetTimeFailWithPO() throws Exception {
3480 setupProfileOwner();
3481 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3482 }
3483
3484 public void testSetTimeWithAutoTimeOn() throws Exception {
3485 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3486 setupDeviceOwner();
3487 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3488 .thenReturn(1);
3489 assertFalse(dpm.setTime(admin1, 0));
3490 }
3491
3492 public void testSetTimeZone() throws Exception {
3493 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3494 setupDeviceOwner();
3495 dpm.setTimeZone(admin1, "Asia/Shanghai");
3496 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3497 }
3498
3499 public void testSetTimeZoneFailWithPO() throws Exception {
3500 setupProfileOwner();
3501 assertExpectException(SecurityException.class, null,
3502 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3503 }
3504
3505 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3506 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3507 setupDeviceOwner();
3508 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3509 .thenReturn(1);
3510 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3511 }
3512
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003513 public void testGetLastBugReportRequestTime() throws Exception {
3514 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3515 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003516
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003517 mContext.packageName = admin1.getPackageName();
3518 mContext.applicationInfo = new ApplicationInfo();
3519 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3520 .thenReturn(Color.WHITE);
3521 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3522 anyObject())).thenReturn(Color.WHITE);
3523
Esteban Talaverad36dd152016-12-15 08:51:45 +00003524 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3525 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003526 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003527
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003528 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003529 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003530
3531 // Requesting a bug report should update the timestamp.
3532 final long beforeRequest = System.currentTimeMillis();
3533 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003534 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003535 final long afterRequest = System.currentTimeMillis();
3536 assertTrue(bugReportRequestTime >= beforeRequest);
3537 assertTrue(bugReportRequestTime <= afterRequest);
3538
3539 // Checking the timestamp again should not change it.
3540 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003541 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003542
3543 // Restarting the DPMS should not lose the timestamp.
3544 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003545 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003546
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003547 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3548 mContext.binder.callingUid = 1234567;
3549 mContext.callerPermissions.add(permission.MANAGE_USERS);
3550 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3551 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3552
3553 // System can retrieve the timestamp.
3554 mContext.binder.clearCallingIdentity();
3555 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3556
3557 // Removing the device owner should clear the timestamp.
3558 clearDeviceOwner();
3559 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003560 }
3561
3562 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3563 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3564 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003565 mContext.packageName = admin1.getPackageName();
3566 mContext.applicationInfo = new ApplicationInfo();
3567 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3568 .thenReturn(Color.WHITE);
3569 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3570 anyObject())).thenReturn(Color.WHITE);
3571
3572 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3573 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003574 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003575 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003576 .thenReturn(true);
3577
3578 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003579 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003580
3581 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3582 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003583 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003584
3585 // Enabling logging should not change the timestamp.
3586 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003587 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003588
3589 // Retrieving the logs should update the timestamp.
3590 final long beforeRetrieval = System.currentTimeMillis();
3591 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003592 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003593 final long afterRetrieval = System.currentTimeMillis();
3594 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3595 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3596
3597 // Checking the timestamp again should not change it.
3598 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003599 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003600
3601 // Retrieving the logs again should update the timestamp.
3602 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003603 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003604 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3605
3606 // Disabling logging should not change the timestamp.
3607 Thread.sleep(2);
3608 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003609 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003610
3611 // Restarting the DPMS should not lose the timestamp.
3612 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003613 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3614
3615 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3616 mContext.binder.callingUid = 1234567;
3617 mContext.callerPermissions.add(permission.MANAGE_USERS);
3618 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3619 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3620
3621 // System can retrieve the timestamp.
3622 mContext.binder.clearCallingIdentity();
3623 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3624
3625 // Removing the device owner should clear the timestamp.
3626 clearDeviceOwner();
3627 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003628 }
3629
Tony Mak2f26b792016-11-28 17:54:51 +00003630 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3631 // Setup device owner.
3632 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3633 setupDeviceOwner();
3634
3635 // Only device owner is setup, the result list should be empty.
3636 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3637 MoreAsserts.assertEmpty(targetUsers);
3638
3639 // Setup a managed profile managed by the same admin.
3640 final int MANAGED_PROFILE_USER_ID = 15;
3641 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3642 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3643
3644 // Add a secondary user, it should never talk with.
3645 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003646 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003647
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003648 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3649 // other.
3650 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3651 MoreAsserts.assertEmpty(targetUsers);
3652
3653 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3654 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3655 MoreAsserts.assertEmpty(targetUsers);
3656
3657 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003658 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003659 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3660 dpm.setAffiliationIds(admin1, userAffiliationIds);
3661
3662 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3663 dpm.setAffiliationIds(admin1, userAffiliationIds);
3664
Tony Mak2f26b792016-11-28 17:54:51 +00003665 // Calling from device owner admin, the result list should just contain the managed
3666 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003667 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003668 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3669 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3670
3671 // Calling from managed profile admin, the result list should just contain the system
3672 // user id.
3673 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3674 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3675 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003676
3677 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003678 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003679
3680 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3681 // to each other.
3682 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3683 MoreAsserts.assertEmpty(targetUsers);
3684
3685 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3686 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3687 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003688 }
3689
3690 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3691 // Setup a device owner.
3692 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3693 setupDeviceOwner();
3694
3695 // Set up a managed profile managed by different package.
3696 final int MANAGED_PROFILE_USER_ID = 15;
3697 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3698 final ComponentName adminDifferentPackage =
3699 new ComponentName("another.package", "whatever.class");
3700 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3701
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003702 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003703 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003704 dpm.setAffiliationIds(admin1, userAffiliationIds);
3705
3706 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3707 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3708
Tony Mak2f26b792016-11-28 17:54:51 +00003709 // Calling from device owner admin, we should get zero bind device admin target users as
3710 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003711 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003712 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3713 MoreAsserts.assertEmpty(targetUsers);
3714
3715 // Calling from managed profile admin, we should still get zero target users for the same
3716 // reason.
3717 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3718 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3719 MoreAsserts.assertEmpty(targetUsers);
3720 }
3721
Jason Parks3c13b642017-11-28 15:39:43 -06003722 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003723 verifyLockTaskState(userId, new String[0],
3724 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003725 }
3726
3727 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3728 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003729 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003730 }
3731
3732 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3733 int flags) throws Exception {
3734 mContext.binder.callingUid = uid;
3735 dpm.setLockTaskPackages(who, packages);
3736 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3737 for (String p : packages) {
3738 assertTrue(dpm.isLockTaskPermitted(p));
3739 }
3740 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3741 // Test to see if set lock task features can be set
3742 dpm.setLockTaskFeatures(who, flags);
3743 verifyLockTaskState(userId, packages, flags);
3744 }
3745
3746 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3747 int flags) throws Exception {
3748 mContext.binder.callingUid = uid;
3749 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3750 () -> dpm.setLockTaskPackages(who, packages));
3751 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3752 () -> dpm.getLockTaskPackages(who));
3753 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3754 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3755 () -> dpm.setLockTaskFeatures(who, flags));
3756 }
3757
Charles Hee078db72017-10-19 18:03:20 +01003758 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003759 // Setup a device owner.
3760 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3761 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003762 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003763 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003764
3765 // Set up a managed profile managed by different package (package name shouldn't matter)
3766 final int MANAGED_PROFILE_USER_ID = 15;
3767 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3768 final ComponentName adminDifferentPackage =
3769 new ComponentName("another.package", "whatever.class");
3770 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003771 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3772
3773 // Setup a PO on the secondary user
3774 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3775 setAsProfileOwner(admin3);
3776 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003777
3778 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003779 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003780 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003781 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3782 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003783 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3784
3785 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3786 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003787 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3788 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003789 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003790
3791 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3792 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3793 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003794 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003795 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3796 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003797 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003798
3799 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003800 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003801 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3802 dpm.setAffiliationIds(admin1, userAffiliationIds);
3803
3804 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3805 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3806
3807 // Now the managed profile can set lock task packages.
3808 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3809 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3810 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3811 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003812 // And it can set lock task features.
3813 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003814 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003815
3816 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003817 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003818 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3819 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003820 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3821 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003822 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003823 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003824
Jason Parks3c13b642017-11-28 15:39:43 -06003825 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003826 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3827 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003828
3829 }
3830
3831 public void testLockTaskPolicyForProfileOwner() throws Exception {
3832 // Setup a PO
3833 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3834 setAsProfileOwner(admin1);
3835 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3836
3837 final String[] poPackages = {"poPackage1", "poPackage2"};
3838 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003839 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3840 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003841 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3842 poPackages, poFlags);
3843
3844 // Set up a managed profile managed by different package (package name shouldn't matter)
3845 final int MANAGED_PROFILE_USER_ID = 15;
3846 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3847 final ComponentName adminDifferentPackage =
3848 new ComponentName("another.package", "whatever.class");
3849 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3850 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3851
3852 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3853 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3854 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3855 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003856 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3857 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003858 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003859 }
3860
Benjamin Franzcaffa772018-02-05 16:36:10 +00003861 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3862 // Setup a device owner.
3863 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3864 setupDeviceOwner();
3865 // Lock task policy is updated when loading user data.
3866 verifyLockTaskState(UserHandle.USER_SYSTEM);
3867
3868 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3869 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3870 assertExpectException(IllegalArgumentException.class,
3871 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3872 () -> dpm.setLockTaskFeatures(admin1, flags));
3873 }
3874
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003875 public void testIsDeviceManaged() throws Exception {
3876 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3877 setupDeviceOwner();
3878
3879 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3880 // find out that the device has a device owner.
3881 assertTrue(dpm.isDeviceManaged());
3882 mContext.binder.callingUid = 1234567;
3883 mContext.callerPermissions.add(permission.MANAGE_USERS);
3884 assertTrue(dpm.isDeviceManaged());
3885 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3886 mContext.binder.clearCallingIdentity();
3887 assertTrue(dpm.isDeviceManaged());
3888
3889 clearDeviceOwner();
3890
3891 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3892 // not have a device owner.
3893 mContext.binder.callingUid = 1234567;
3894 mContext.callerPermissions.add(permission.MANAGE_USERS);
3895 assertFalse(dpm.isDeviceManaged());
3896 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3897 mContext.binder.clearCallingIdentity();
3898 assertFalse(dpm.isDeviceManaged());
3899 }
3900
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003901 public void testDeviceOwnerOrganizationName() throws Exception {
3902 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3903 setupDeviceOwner();
3904
3905 dpm.setOrganizationName(admin1, "organization");
3906
3907 // Device owner can retrieve organization managing the device.
3908 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3909
3910 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3911 mContext.binder.callingUid = 1234567;
3912 mContext.callerPermissions.add(permission.MANAGE_USERS);
3913 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3914 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3915
3916 // System can retrieve organization managing the device.
3917 mContext.binder.clearCallingIdentity();
3918 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3919
3920 // Removing the device owner clears the organization managing the device.
3921 clearDeviceOwner();
3922 assertNull(dpm.getDeviceOwnerOrganizationName());
3923 }
3924
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003925 public void testWipeDataManagedProfile() throws Exception {
3926 final int MANAGED_PROFILE_USER_ID = 15;
3927 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3928 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3929 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3930
3931 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003932 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003933 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003934 // Get mock reason string since we throw an IAE with empty string input.
3935 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3936 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003937
3938 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003939 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003940 MANAGED_PROFILE_USER_ID);
3941 }
3942
3943 public void testWipeDataManagedProfileDisallowed() throws Exception {
3944 final int MANAGED_PROFILE_USER_ID = 15;
3945 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3946 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3947
3948 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003949 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003950 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3951
Pavel Grafov75c0a892017-05-18 17:28:27 +01003952 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003953 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3954 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3955 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003956 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3957 thenReturn("Just a test string.");
3958
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003959 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003960 // The PO is not allowed to remove the profile if the user restriction was set on the
3961 // profile by the system
3962 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3963 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003964 }
3965
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003966 public void testWipeDataDeviceOwner() throws Exception {
3967 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003968 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003969 UserManager.DISALLOW_FACTORY_RESET,
3970 UserHandle.SYSTEM))
3971 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003972 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3973 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003974
3975 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003976 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07003977 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3978 /*wipeEuicc=*/ eq(false));
3979 }
3980
3981 public void testWipeEuiccDataEnabled() throws Exception {
3982 setDeviceOwner();
3983 when(getServices().userManager.getUserRestrictionSource(
3984 UserManager.DISALLOW_FACTORY_RESET,
3985 UserHandle.SYSTEM))
3986 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01003987 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3988 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07003989
3990 dpm.wipeData(WIPE_EUICC);
3991 verify(getServices().recoverySystem).rebootWipeUserData(
3992 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
3993 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003994 }
3995
3996 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3997 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01003998 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003999 UserManager.DISALLOW_FACTORY_RESET,
4000 UserHandle.SYSTEM))
4001 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004002 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4003 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004004 // The DO is not allowed to wipe the device if the user restriction was set
4005 // by the system
4006 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4007 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004008 }
4009
4010 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4011 final int MANAGED_PROFILE_USER_ID = 15;
4012 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4013 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4014
4015 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004016 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004017 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4018
Pavel Grafov75c0a892017-05-18 17:28:27 +01004019 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004020 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4021 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4022 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4023
4024 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4025 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4026
4027 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4028 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4029 // Failed password attempts on the parent user are taken into account, as there isn't a
4030 // separate work challenge.
4031 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4032 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4033 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4034
4035 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4036 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004037 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004038 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004039 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004040 }
4041
4042 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4043 throws Exception {
4044 final int MANAGED_PROFILE_USER_ID = 15;
4045 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4046 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4047
4048 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004049 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004050 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4051
Pavel Grafov75c0a892017-05-18 17:28:27 +01004052 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004053 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4054 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4055 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4056
4057 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4058 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4059
4060 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4061 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4062 // Failed password attempts on the parent user are taken into account, as there isn't a
4063 // separate work challenge.
4064 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4065 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4066 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4067
4068 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4069 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004070 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004071 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004072 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004073 }
4074
4075 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4076 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004077 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004078 UserManager.DISALLOW_FACTORY_RESET,
4079 UserHandle.SYSTEM))
4080 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4081
4082 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4083
4084 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4085 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4086 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4087 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4088 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4089
4090 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4091 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004092 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004093 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4094 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004095 }
4096
4097 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4098 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004099 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004100 UserManager.DISALLOW_FACTORY_RESET,
4101 UserHandle.SYSTEM))
4102 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4103
4104 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4105
4106 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4107 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4108 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4109 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4110 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4111
4112 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004113 verifyZeroInteractions(getServices().recoverySystem);
4114 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004115 .removeUserEvenWhenDisallowed(anyInt());
4116 }
4117
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004118 public void testGetPermissionGrantState() throws Exception {
4119 final String permission = "some.permission";
4120 final String app1 = "com.example.app1";
4121 final String app2 = "com.example.app2";
4122
Pavel Grafov75c0a892017-05-18 17:28:27 +01004123 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004124 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004125 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004126 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004127 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004128 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4129 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004130 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004131 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004132 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004133 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004134 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004135 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4136
4137 // System can retrieve permission grant state.
4138 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004139 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004140 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4141 dpm.getPermissionGrantState(null, app1, permission));
4142 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4143 dpm.getPermissionGrantState(null, app2, permission));
4144
4145 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004146 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4147 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004148 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4149 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004150
4151 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004152 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4153 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004154 setAsProfileOwner(admin1);
4155 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4156 dpm.getPermissionGrantState(admin1, app1, permission));
4157 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4158 dpm.getPermissionGrantState(admin1, app2, permission));
4159 }
4160
Rubin Xuaab7a412016-12-30 21:13:29 +00004161 public void testResetPasswordWithToken() throws Exception {
4162 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4163 setupDeviceOwner();
4164 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004165 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4166 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4167
Rubin Xuaab7a412016-12-30 21:13:29 +00004168 // test adding a token
4169 final byte[] token = new byte[32];
4170 final long handle = 123456;
4171 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004172 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4173 nullable(EscrowTokenStateChangeCallback.class)))
4174 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004175 assertTrue(dpm.setResetPasswordToken(admin1, token));
4176
4177 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004178 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004179 .thenReturn(true);
4180 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4181
4182 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004183 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004184 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004185 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004186 eq(UserHandle.USER_SYSTEM)))
4187 .thenReturn(true);
4188 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4189
4190 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004191 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004192 .thenReturn(true);
4193 assertTrue(dpm.clearResetPasswordToken(admin1));
4194 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004195
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004196 public void testIsActivePasswordSufficient() throws Exception {
4197 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4198 mContext.packageName = admin1.getPackageName();
4199 setupDeviceOwner();
4200
4201 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4202 dpm.setPasswordMinimumLength(admin1, 8);
4203 dpm.setPasswordMinimumLetters(admin1, 6);
4204 dpm.setPasswordMinimumLowerCase(admin1, 3);
4205 dpm.setPasswordMinimumUpperCase(admin1, 1);
4206 dpm.setPasswordMinimumNonLetter(admin1, 1);
4207 dpm.setPasswordMinimumNumeric(admin1, 1);
4208 dpm.setPasswordMinimumSymbols(admin1, 0);
4209
Rubin Xucc391c22018-01-02 20:37:35 +00004210 reset(mContext.spiedContext);
4211
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004212 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4213 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4214 8, 2,
4215 6, 1,
4216 0, 1);
4217
4218 setActivePasswordState(passwordMetricsNoSymbols);
4219 assertTrue(dpm.isActivePasswordSufficient());
4220
4221 initializeDpms();
4222 reset(mContext.spiedContext);
4223 assertTrue(dpm.isActivePasswordSufficient());
4224
4225 // This call simulates the user entering the password for the first time after a reboot.
4226 // This causes password metrics to be reloaded into memory. Until this happens,
4227 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4228 // even if the DPC changes password requirements so that the password no longer meets the
4229 // requirements. This is a known limitation of the current implementation of
4230 // isActivePasswordSufficient() - see b/34218769.
4231 setActivePasswordState(passwordMetricsNoSymbols);
4232 assertTrue(dpm.isActivePasswordSufficient());
4233
4234 dpm.setPasswordMinimumSymbols(admin1, 1);
4235 // This assertion would fail if we had not called setActivePasswordState() again after
4236 // initializeDpms() - see previous comment.
4237 assertFalse(dpm.isActivePasswordSufficient());
4238
4239 initializeDpms();
4240 reset(mContext.spiedContext);
4241 assertFalse(dpm.isActivePasswordSufficient());
4242
4243 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4244 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4245 7, 2,
4246 5, 1,
4247 1, 2);
4248
4249 setActivePasswordState(passwordMetricsWithSymbols);
4250 assertTrue(dpm.isActivePasswordSufficient());
4251 }
4252
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004253 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4254 // If there is no lock screen, the password is considered empty no matter what, because
4255 // it provides no security.
4256 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4257
4258 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4259 mContext.packageName = admin1.getPackageName();
4260 setupDeviceOwner();
4261
4262 // If no password requirements are set, isActivePasswordSufficient should succeed.
4263 assertTrue(dpm.isActivePasswordSufficient());
4264
4265 // Now set some password quality requirements.
4266 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4267
4268 reset(mContext.spiedContext);
4269 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4270 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4271 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4272 8, 2,
4273 6, 1,
4274 0, 1);
4275 // This should be ignored, as there is no lock screen.
4276 dpm.setActivePasswordState(passwordMetricsNoSymbols, userHandle);
4277 dpm.reportPasswordChanged(userHandle);
4278
4279 // No broadcast should be sent.
4280 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4281 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4282 MockUtils.checkUserHandle(userHandle));
4283
4284 // The active (nonexistent) password doesn't comply with the requirements.
4285 assertFalse(dpm.isActivePasswordSufficient());
4286 }
4287
Pavel Grafov75c0a892017-05-18 17:28:27 +01004288 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4289 throws Exception {
4290 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004291 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004292
Pavel Grafov75c0a892017-05-18 17:28:27 +01004293 dpm.setActivePasswordState(passwordMetrics, userHandle);
4294 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004295
Rubin Xucc391c22018-01-02 20:37:35 +00004296 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4297 // reportPasswordChanged()
Eran Messeri9ecde422018-04-30 16:16:39 +01004298 // This broadcast should be sent 4 times:
4299 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4300 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
4301 // * Twice from calls to DevicePolicyManagerService.saveSettingsLocked
4302 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4303 // the password change is relevant to and another with the credential owner of said
4304 // userId.
4305 verify(mContext.spiedContext, times(4)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004306 MockUtils.checkIntentAction(
4307 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4308 MockUtils.checkUserHandle(userHandle));
4309
Pavel Grafov75c0a892017-05-18 17:28:27 +01004310 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4311 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004312 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004313
4314 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4315 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004316 MockUtils.checkUserHandle(userHandle),
4317 eq(null),
4318 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004319
4320 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4321 // let it finish with system uid, otherwise it will throw and crash.
4322 flushTasks();
4323
4324 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004325 }
4326
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004327 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4328 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4329 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4330 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4331 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4332 DpmMockContext.SYSTEM_UID);
4333 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4334 DpmMockContext.SYSTEM_UID);
4335
4336 // Set up a device owner.
4337 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004338 setupDeviceOwner();
4339
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004340 // First and second user set IMEs manually.
4341 mContext.binder.callingUid = firstUserSystemUid;
4342 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4343 mContext.binder.callingUid = secondUserSystemUid;
4344 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004345
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004346 // Device owner changes IME for first user.
4347 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004348 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004349 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004350 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004351 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004352 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004353 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004354 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4355 mContext.binder.callingUid = firstUserSystemUid;
4356 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4357 mContext.binder.callingUid = secondUserSystemUid;
4358 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004359
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004360 // Second user changes IME manually.
4361 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4362 mContext.binder.callingUid = firstUserSystemUid;
4363 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4364 mContext.binder.callingUid = secondUserSystemUid;
4365 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004366
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004367 // First user changes IME manually.
4368 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4369 mContext.binder.callingUid = firstUserSystemUid;
4370 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4371 mContext.binder.callingUid = secondUserSystemUid;
4372 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004373
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004374 // Device owner changes IME for first user again.
4375 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004376 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004377 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004378 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004379 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004380 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004381 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4382 mContext.binder.callingUid = firstUserSystemUid;
4383 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4384 mContext.binder.callingUid = secondUserSystemUid;
4385 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004386
4387 // Restarting the DPMS should not lose information.
4388 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004389 mContext.binder.callingUid = firstUserSystemUid;
4390 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4391 mContext.binder.callingUid = secondUserSystemUid;
4392 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004393
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004394 // Device owner can find out whether it set the current IME itself.
4395 mContext.binder.callingUid = deviceOwnerUid;
4396 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004397
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004398 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004399 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004400 mContext.binder.callingUid = firstUserSystemUid;
4401 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4402 mContext.binder.callingUid = secondUserSystemUid;
4403 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004404 }
4405
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004406 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4407 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4408 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4409 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4410 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4411 DpmMockContext.SYSTEM_UID);
4412 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4413 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004414
4415 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004416 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004417 setupProfileOwner();
4418
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004419 // First and second user set IMEs manually.
4420 mContext.binder.callingUid = firstUserSystemUid;
4421 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4422 mContext.binder.callingUid = secondUserSystemUid;
4423 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004424
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004425 // Profile owner changes IME for second user.
4426 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004427 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004428 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004429 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004430 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004431 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004432 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004433 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4434 mContext.binder.callingUid = firstUserSystemUid;
4435 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4436 mContext.binder.callingUid = secondUserSystemUid;
4437 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004438
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004439 // First user changes IME manually.
4440 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4441 mContext.binder.callingUid = firstUserSystemUid;
4442 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4443 mContext.binder.callingUid = secondUserSystemUid;
4444 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004445
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004446 // Second user changes IME manually.
4447 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4448 mContext.binder.callingUid = firstUserSystemUid;
4449 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4450 mContext.binder.callingUid = secondUserSystemUid;
4451 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004452
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004453 // Profile owner changes IME for second user again.
4454 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004455 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004456 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004457 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004458 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004459 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004460 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4461 mContext.binder.callingUid = firstUserSystemUid;
4462 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4463 mContext.binder.callingUid = secondUserSystemUid;
4464 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004465
4466 // Restarting the DPMS should not lose information.
4467 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004468 mContext.binder.callingUid = firstUserSystemUid;
4469 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4470 mContext.binder.callingUid = secondUserSystemUid;
4471 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004472
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004473 // Profile owner can find out whether it set the current IME itself.
4474 mContext.binder.callingUid = profileOwnerUid;
4475 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004476
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004477 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004478 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004479 mContext.binder.callingUid = firstUserSystemUid;
4480 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4481 mContext.binder.callingUid = secondUserSystemUid;
4482 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004483 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004484
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004485 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4486 throws Exception {
4487 // Set up a device owner.
4488 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4489 setupDeviceOwner();
4490 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4491 }
4492
4493 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4494 throws Exception {
4495 // Set up a profile owner.
4496 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4497 setupProfileOwner();
4498 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4499 }
4500
4501 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4502 int adminUid) throws Exception {
4503 mContext.binder.callingUid = adminUid;
4504 final int userId = UserHandle.getUserId(adminUid);
4505
4506 final String packageName = "some.package";
4507 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4508 admin1, Collections.singletonList(packageName)));
4509 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4510
4511 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4512 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4513
4514 // Attempt to set to empty list (which means no listener is whitelisted)
4515 mContext.binder.callingUid = adminUid;
4516 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004517 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004518 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4519
4520 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4521 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4522 }
4523
4524 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4525 // Set up a managed profile
4526 final int MANAGED_PROFILE_USER_ID = 15;
4527 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4528 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4529 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4530
4531 final String permittedListener = "some.package";
4532 setupPackageInPackageManager(
4533 permittedListener,
4534 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4535 /*appId=*/ 12345, /*flags=*/ 0);
4536
4537 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4538 admin1, Collections.singletonList(permittedListener)));
4539
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004540 // isNotificationListenerServicePermitted should throw if not called from System.
4541 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4542 () -> dpms.isNotificationListenerServicePermitted(
4543 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004544
4545 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4546 assertTrue(dpms.isNotificationListenerServicePermitted(
4547 permittedListener, MANAGED_PROFILE_USER_ID));
4548 }
4549
4550 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4551 throws Exception {
4552 // Set up a managed profile
4553 final int MANAGED_PROFILE_USER_ID = 15;
4554 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4555 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4556 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4557
4558 final String permittedListener = "permitted.package";
4559 int appId = 12345;
4560 setupPackageInPackageManager(
4561 permittedListener,
4562 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4563 appId, /*flags=*/ 0);
4564
4565 final String notPermittedListener = "not.permitted.package";
4566 setupPackageInPackageManager(
4567 notPermittedListener,
4568 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4569 ++appId, /*flags=*/ 0);
4570
4571 final String systemListener = "system.package";
4572 setupPackageInPackageManager(
4573 systemListener,
4574 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4575 ++appId, ApplicationInfo.FLAG_SYSTEM);
4576
4577 // By default all packages are allowed
4578 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4579
4580 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4581 assertTrue(dpms.isNotificationListenerServicePermitted(
4582 permittedListener, MANAGED_PROFILE_USER_ID));
4583 assertTrue(dpms.isNotificationListenerServicePermitted(
4584 notPermittedListener, MANAGED_PROFILE_USER_ID));
4585 assertTrue(dpms.isNotificationListenerServicePermitted(
4586 systemListener, MANAGED_PROFILE_USER_ID));
4587
4588 // Setting only one package in the whitelist
4589 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4590 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4591 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004592 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004593 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4594 assertEquals(1, permittedListeners.size());
4595 assertEquals(permittedListener, permittedListeners.get(0));
4596
4597 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4598 assertTrue(dpms.isNotificationListenerServicePermitted(
4599 permittedListener, MANAGED_PROFILE_USER_ID));
4600 assertFalse(dpms.isNotificationListenerServicePermitted(
4601 notPermittedListener, MANAGED_PROFILE_USER_ID));
4602 // System packages are always allowed (even if not in the whitelist)
4603 assertTrue(dpms.isNotificationListenerServicePermitted(
4604 systemListener, MANAGED_PROFILE_USER_ID));
4605
4606 // Setting an empty whitelist - only system listeners allowed
4607 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4608 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004609 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004610 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4611
4612 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4613 assertFalse(dpms.isNotificationListenerServicePermitted(
4614 permittedListener, MANAGED_PROFILE_USER_ID));
4615 assertFalse(dpms.isNotificationListenerServicePermitted(
4616 notPermittedListener, MANAGED_PROFILE_USER_ID));
4617 // System packages are always allowed (even if not in the whitelist)
4618 assertTrue(dpms.isNotificationListenerServicePermitted(
4619 systemListener, MANAGED_PROFILE_USER_ID));
4620
4621 // Setting a null whitelist - all listeners allowed
4622 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4623 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4624 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4625
4626 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4627 assertTrue(dpms.isNotificationListenerServicePermitted(
4628 permittedListener, MANAGED_PROFILE_USER_ID));
4629 assertTrue(dpms.isNotificationListenerServicePermitted(
4630 notPermittedListener, MANAGED_PROFILE_USER_ID));
4631 assertTrue(dpms.isNotificationListenerServicePermitted(
4632 systemListener, MANAGED_PROFILE_USER_ID));
4633 }
4634
4635 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4636 throws Exception {
4637 // Set up a managed profile
4638 final int MANAGED_PROFILE_USER_ID = 15;
4639 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4640 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4641 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4642
4643 final String nonSystemPackage = "non.system.package";
4644 int appId = 12345;
4645 setupPackageInPackageManager(
4646 nonSystemPackage,
4647 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4648 appId, /*flags=*/ 0);
4649
4650 final String systemListener = "system.package";
4651 setupPackageInPackageManager(
4652 systemListener,
4653 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4654 ++appId, ApplicationInfo.FLAG_SYSTEM);
4655
4656 // By default all packages are allowed (for all profiles)
4657 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4658
4659 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4660 assertTrue(dpms.isNotificationListenerServicePermitted(
4661 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4662 assertTrue(dpms.isNotificationListenerServicePermitted(
4663 systemListener, MANAGED_PROFILE_USER_ID));
4664 assertTrue(dpms.isNotificationListenerServicePermitted(
4665 nonSystemPackage, UserHandle.USER_SYSTEM));
4666 assertTrue(dpms.isNotificationListenerServicePermitted(
4667 systemListener, UserHandle.USER_SYSTEM));
4668
4669 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4670 // all allowed in primary profile
4671 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4672 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004673 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004674 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4675
4676 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4677 assertFalse(dpms.isNotificationListenerServicePermitted(
4678 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4679 assertTrue(dpms.isNotificationListenerServicePermitted(
4680 systemListener, MANAGED_PROFILE_USER_ID));
4681 assertTrue(dpms.isNotificationListenerServicePermitted(
4682 nonSystemPackage, UserHandle.USER_SYSTEM));
4683 assertTrue(dpms.isNotificationListenerServicePermitted(
4684 systemListener, UserHandle.USER_SYSTEM));
4685 }
4686
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004687 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004688 mServiceContext.packageName = mRealTestContext.getPackageName();
4689 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4690 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004691 setDeviceOwner();
4692
Pavel Grafov75c0a892017-05-18 17:28:27 +01004693 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004694 }
4695
4696 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004697 mServiceContext.packageName = mRealTestContext.getPackageName();
4698 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4699 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004700 setAsProfileOwner(admin1);
4701
Pavel Grafov75c0a892017-05-18 17:28:27 +01004702 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4703 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004704 }
4705
4706 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004707 mServiceContext.packageName = mRealTestContext.getPackageName();
4708 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4709 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004710 setAsProfileOwner(admin1);
4711
Pavel Grafov75c0a892017-05-18 17:28:27 +01004712 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4713 caller.packageName = "com.example.delegate";
4714 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4715 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004716
Pavel Grafov75c0a892017-05-18 17:28:27 +01004717 // Make caller a delegated cert installer.
4718 runAsCaller(mAdmin1Context, dpms,
4719 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004720
4721 verifyCanGetOwnerInstalledCaCerts(null, caller);
4722 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004723 }
4724
Rubin Xucc391c22018-01-02 20:37:35 +00004725 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004726 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4727 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004728 Bundle restriction = new Bundle();
4729 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4730
4731 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4732 RestrictionsListener listener = new RestrictionsListener(mContext);
4733 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4734 new Bundle());
4735 verifyDataSharingChangedBroadcast();
4736 }
4737
4738 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004739 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4740 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004741 Bundle restriction = new Bundle();
4742 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4743
4744 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4745 RestrictionsListener listener = new RestrictionsListener(mContext);
4746 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4747 restriction);
4748 verifyDataSharingChangedBroadcast();
4749 }
4750
4751 public void testDisallowSharingIntoProfileUnchanged() {
4752 RestrictionsListener listener = new RestrictionsListener(mContext);
4753 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4754 new Bundle());
4755 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4756 }
4757
4758 private void verifyDataSharingChangedBroadcast() {
4759 Intent expectedIntent = new Intent(
4760 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4761 expectedIntent.setPackage("com.android.managedprovisioning");
4762 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4763 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4764 MockUtils.checkIntent(expectedIntent),
4765 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4766 }
4767
yuemingwe3d9c092018-01-11 12:11:44 +00004768 public void testOverrideApnAPIsFailWithPO() throws Exception {
4769 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004770 ApnSetting apn = (new ApnSetting.Builder())
4771 .setApnName("test")
4772 .setEntryName("test")
4773 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4774 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004775 assertExpectException(SecurityException.class, null, () ->
4776 dpm.addOverrideApn(admin1, apn));
4777 assertExpectException(SecurityException.class, null, () ->
4778 dpm.updateOverrideApn(admin1, 0, apn));
4779 assertExpectException(SecurityException.class, null, () ->
4780 dpm.removeOverrideApn(admin1, 0));
4781 assertExpectException(SecurityException.class, null, () ->
4782 dpm.getOverrideApns(admin1));
4783 assertExpectException(SecurityException.class, null, () ->
4784 dpm.setOverrideApnsEnabled(admin1, false));
4785 assertExpectException(SecurityException.class, null, () ->
4786 dpm.isOverrideApnEnabled(admin1));
4787 }
4788
Robin Lee2c68dad2017-03-17 12:50:24 +00004789 private void verifyCanGetOwnerInstalledCaCerts(
4790 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004791 final String alias = "cert";
4792 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004793
4794 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004796 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4797 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004798 }
4799 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4800
4801 // caller: device admin or delegated certificate installer
4802 callerContext.applicationInfo = new ApplicationInfo();
4803 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4804
4805 // system_server
4806 final DpmMockContext serviceContext = mContext;
4807 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004808 getServices().addPackageContext(callerUser, admin1Context);
4809 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004810
4811 // Install a CA cert.
4812 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004813 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004814 .thenReturn(alias);
4815 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004816 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004817 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004818 });
4819
Pavel Grafov75c0a892017-05-18 17:28:27 +01004820 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4821 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4822 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004823 flushTasks();
4824
Robin Lee2c68dad2017-03-17 12:50:24 +00004825 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4826
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004827 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004828 runAsCaller(admin1Context, dpms, (dpm) -> {
4829 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004830 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004831 ownerInstalledCaCerts.addAll(installedCaCerts);
4832 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004833
4834 // Restarting the DPMS should not lose information.
4835 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004836 runAsCaller(admin1Context, dpms, (dpm) ->
4837 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004838
4839 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004840 runAsCaller(serviceContext, dpms, (dpm) -> {
4841 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004842
Robin Lee2c68dad2017-03-17 12:50:24 +00004843 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004844 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004845 });
4846
Pavel Grafov75c0a892017-05-18 17:28:27 +01004847 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4848 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4849 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004850 flushTasks();
4851
4852 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4853 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004854 runAsCaller(admin1Context, dpms, (dpm) -> {
4855 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4856 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004857 }
4858
Robin Lee2c68dad2017-03-17 12:50:24 +00004859 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4860 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004861 final String alias = "cert";
4862 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004863
4864 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004865 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004866 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4867 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004868 }
4869 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4870
4871 // caller: device admin or delegated certificate installer
4872 callerContext.applicationInfo = new ApplicationInfo();
4873 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4874
4875 // system_server
4876 final DpmMockContext serviceContext = mContext;
4877 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004878 getServices().addPackageContext(callerUser, admin1Context);
4879 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004880
4881 // Install a CA cert as caller
4882 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004883 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004884 .thenReturn(alias);
4885 assertTrue(dpm.installCaCert(callerName, caCert));
4886 });
4887
4888 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004889 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004890 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004891 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4892 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4893 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004894 flushTasks();
4895
Robin Lee2c68dad2017-03-17 12:50:24 +00004896 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004897 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004898
4899 runAsCaller(serviceContext, dpms, (dpm) -> {
4900 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4901 assertNotNull(ownerInstalledCaCerts);
4902 assertTrue(ownerInstalledCaCerts.isEmpty());
4903 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004904 }
4905
Eran Messeri94d56762017-12-21 20:50:54 +00004906 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4907 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4908 Arrays.sort(gotFlags);
4909 Arrays.sort(expectedFlags);
4910 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4911 }
4912
4913 public void testTranslationOfIdAttestationFlag() {
4914 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4915 int[] correspondingAttUtilsTypes = new int[]{
4916 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4917 AttestationUtils.ID_TYPE_MEID};
4918
4919 // Test translation of zero flags
4920 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4921
4922 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4923 // non-null array
4924 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4925
4926 // Test translation of a single flag
4927 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4928 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4929 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4930
4931 // Test translation of two flags
4932 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4933 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4934 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4935 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4936
4937 // Test translation of all three flags
4938 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4939 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4940 AttestationUtils.ID_TYPE_MEID});
4941 // Test translation of all three flags
4942 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4943 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4944 AttestationUtils.ID_TYPE_MEID});
4945 }
4946
arangelov08d534b2018-01-22 15:20:53 +00004947 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4948 setDeviceOwner();
4949 initializeDpms();
4950 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4951 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4952 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4953 }
4954
4955 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4956 DpmTestUtils.writeInputStreamToFile(
4957 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4958 getDeviceOwnerPoliciesFile());
4959 DpmTestUtils.writeInputStreamToFile(
4960 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4961 getDeviceOwnerFile());
4962 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4963 }
4964
4965 public void testRevertDeviceOwnership_deviceNotMigrated()
4966 throws Exception {
4967 DpmTestUtils.writeInputStreamToFile(
4968 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4969 getDeviceOwnerPoliciesFile());
4970 DpmTestUtils.writeInputStreamToFile(
4971 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4972 getDeviceOwnerFile());
4973 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4974 }
4975
4976 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
4977 throws Exception {
4978 DpmTestUtils.writeInputStreamToFile(
4979 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
4980 getDeviceOwnerPoliciesFile());
4981 DpmTestUtils.writeInputStreamToFile(
4982 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
4983 getDeviceOwnerFile());
4984 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4985 }
4986
4987 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
4988 setupProfileOwner();
4989 initializeDpms();
4990 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4991 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
4992 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
4993 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
4994 }
4995
4996 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
4997 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
4998 UserHandle.USER_SYSTEM);
4999 DpmTestUtils.writeInputStreamToFile(
5000 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5001 getProfileOwnerPoliciesFile());
5002 DpmTestUtils.writeInputStreamToFile(
5003 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5004 getProfileOwnerFile());
5005 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5006 }
5007
5008 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5009 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5010 UserHandle.USER_SYSTEM);
5011 DpmTestUtils.writeInputStreamToFile(
5012 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5013 getProfileOwnerPoliciesFile());
5014 DpmTestUtils.writeInputStreamToFile(
5015 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5016 getProfileOwnerFile());
5017 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5018 }
5019
5020 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5021 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5022 UserHandle.USER_SYSTEM);
5023 DpmTestUtils.writeInputStreamToFile(
5024 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5025 getProfileOwnerPoliciesFile());
5026 DpmTestUtils.writeInputStreamToFile(
5027 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5028 getProfileOwnerFile());
5029 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5030 }
5031
Eran Messeribb271892018-10-17 18:27:50 +01005032 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5033 setupProfileOwner();
5034 configureContextForAccess(mContext, false);
5035
5036 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005037 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005038 }
5039
5040 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5041 setupProfileOwner();
5042 configureContextForAccess(mContext, false);
5043
5044 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005045 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005046 }
5047
5048 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5049 setupProfileOwner();
5050
5051 // This method will throw if the system context could not call
5052 // setProfileOwnerCanAccessDeviceIds successfully.
5053 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5054 }
5055
5056 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5057 when(context.spiedContext.checkCallingPermission(
5058 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5059 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5060 : PackageManager.PERMISSION_DENIED);
5061 }
5062
5063 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5064 setupProfileOwner();
5065
5066 final long ident = mServiceContext.binder.clearCallingIdentity();
5067 configureContextForAccess(mServiceContext, true);
5068
5069 mServiceContext.binder.callingUid =
5070 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5071 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5072 try {
5073 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005074 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005075 });
5076 } finally {
5077 mServiceContext.binder.restoreCallingIdentity(ident);
5078 }
5079 }
5080
5081 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5082 throws Exception {
5083 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5084 setupDeviceOwner();
5085 configureContextForAccess(mContext, false);
5086
5087 // Device owner should be allowed to request Device ID attestation.
5088 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5089 DpmMockContext.CALLER_SYSTEM_USER_UID);
5090
5091 // Another package must not be allowed to request Device ID attestation.
5092 assertExpectException(SecurityException.class, null,
5093 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5094 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5095 // Another component that is not the admin must not be allowed to request Device ID
5096 // attestation.
5097 assertExpectException(SecurityException.class, null,
5098 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5099 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5100 }
5101
5102 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5103 throws Exception {
5104 configureContextForAccess(mContext, false);
5105
5106 // Make sure a security exception is thrown if the device has no profile owner.
5107 assertExpectException(SecurityException.class, null,
5108 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5109 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5110
5111 setupProfileOwner();
5112 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5113
5114 // The profile owner is allowed to request Device ID attestation.
5115 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5116 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5117 DpmMockContext.CALLER_UID);
5118 // But not another package.
5119 assertExpectException(SecurityException.class, null,
5120 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5121 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5122 // Or another component which is not the admin.
5123 assertExpectException(SecurityException.class, null,
5124 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5125 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5126 }
5127
5128 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5129 final long ident = mServiceContext.binder.clearCallingIdentity();
5130
5131 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5132 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5133 try {
5134 runAsCaller(mServiceContext, dpms, action);
5135 } finally {
5136 mServiceContext.binder.restoreCallingIdentity(ident);
5137 }
5138 }
5139
5140 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5141 setupProfileOwner();
5142 markDelegatedCertInstallerAsInstalled();
5143
5144 // Configure a delegated cert installer.
5145 runAsCaller(mServiceContext, dpms,
5146 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5147 Arrays.asList(DELEGATION_CERT_INSTALL)));
5148
5149 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5150
5151 // Make sure that the profile owner can still request Device ID attestation.
5152 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5153 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5154 DpmMockContext.CALLER_UID);
5155
5156 runAsDelegatedCertInstaller(dpm -> {
5157 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5158 DpmMockContext.DELEGATE_PACKAGE_NAME,
5159 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5160 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5161 });
5162 }
5163
5164 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5165 throws Exception {
5166 setupProfileOwner();
5167 markDelegatedCertInstallerAsInstalled();
5168
5169 // Configure a delegated cert installer.
5170 runAsCaller(mServiceContext, dpms,
5171 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5172 Arrays.asList(DELEGATION_CERT_INSTALL)));
5173
5174
5175 assertExpectException(SecurityException.class, null,
5176 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5177 admin1.getPackageName(),
5178 DpmMockContext.CALLER_UID));
5179
5180 runAsDelegatedCertInstaller(dpm -> {
5181 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5182 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5183 DpmMockContext.DELEGATE_PACKAGE_NAME,
5184 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5185 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5186 });
5187 }
5188
Bernard Chaue9586552018-11-29 10:59:31 +00005189 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5190 assertThrows(SecurityException.class,
5191 () -> new DevicePolicyManagerTestable(
5192 mServiceContext,
5193 dpms,
5194 /* parentInstance= */ true)
5195 .getPasswordComplexity());
5196 }
5197
5198 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5199 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5200 .thenReturn(false);
5201 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5202 }
5203
5204 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5205 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5206 .thenReturn(true);
5207 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5208 }
5209
5210
5211 public void testGetPasswordComplexity_currentUserNoPassword() {
5212 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5213 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005214 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005215 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5216 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5217
5218 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5219 }
5220
5221 public void testGetPasswordComplexity_currentUserHasPassword() {
5222 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5223 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005224 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005225 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5226 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5227 dpms.mUserPasswordMetrics.put(
5228 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005229 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005230
5231 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5232 }
5233
5234 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5235 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5236 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005237 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005238
5239 UserInfo parentUser = new UserInfo();
5240 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5241 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5242 .thenReturn(parentUser.id);
5243
5244 dpms.mUserPasswordMetrics.put(
5245 DpmMockContext.CALLER_USER_HANDLE,
Rich Canningsf64ec632019-02-21 12:40:36 -08005246 PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005247 dpms.mUserPasswordMetrics.put(
5248 parentUser.id,
Rich Canningsf64ec632019-02-21 12:40:36 -08005249 PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005250
5251 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5252 }
5253
yuemingwd2bfbc82019-01-02 11:42:25 +00005254 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5255 setAsProfileOwner(admin1);
5256 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5257 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5258 }
5259
5260 public void testCrossProfileCalendarPackages_reopenDpms() {
5261 setAsProfileOwner(admin1);
5262 dpm.setCrossProfileCalendarPackages(admin1, null);
5263 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5264 assertTrue(packages == null);
5265 initializeDpms();
5266 packages = dpm.getCrossProfileCalendarPackages(admin1);
5267 assertTrue(packages == null);
5268
5269 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5270 packages = dpm.getCrossProfileCalendarPackages(admin1);
5271 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5272 initializeDpms();
5273 packages = dpm.getCrossProfileCalendarPackages(admin1);
5274 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5275
5276 final String dummyPackageName = "test";
5277 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5278 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5279 packages = dpm.getCrossProfileCalendarPackages(admin1);
5280 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5281 initializeDpms();
5282 packages = dpm.getCrossProfileCalendarPackages(admin1);
5283 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5284 }
5285
5286 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5287 assertTrue(expected != null);
5288 assertTrue(actual != null);
5289 assertTrue(expected.containsAll(actual));
5290 assertTrue(actual.containsAll(expected));
5291 }
5292
yuemingwdded98f2019-01-30 17:08:12 +00005293 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5294 setAsProfileOwner(admin1);
5295 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5296 when(getServices().settings.settingsSecureGetIntForUser(
5297 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5298 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5299 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5300 }
5301
5302 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5303 final String testPackage = "TEST_PACKAGE";
5304 setAsProfileOwner(admin1);
5305 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5306 when(getServices().settings.settingsSecureGetIntForUser(
5307 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5308 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5309 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5310 }
5311
5312 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5313 final String testPackage = "TEST_PACKAGE";
5314 setAsProfileOwner(admin1);
5315 dpm.setCrossProfileCalendarPackages(admin1, null);
5316 when(getServices().settings.settingsSecureGetIntForUser(
5317 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5318 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5319 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5320 }
5321
Eran Messeribb271892018-10-17 18:27:50 +01005322 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5323 final long ident = mServiceContext.binder.clearCallingIdentity();
5324 mServiceContext.binder.callingUid =
5325 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5326 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005327 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005328 });
5329 mServiceContext.binder.restoreCallingIdentity(ident);
5330 }
5331
arangelov08d534b2018-01-22 15:20:53 +00005332 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5333 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5334 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5335 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5336
5337 final long ident = mServiceContext.binder.clearCallingIdentity();
5338 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5339 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5340 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5341 // To simulate a reboot, we just reinitialize dpms and call systemReady
5342 initializeDpms();
5343
5344 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5345 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5346 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5347 assertTrue(dpm.isAdminActive(admin1));
5348 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5349 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5350
5351 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5352 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5353 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5354 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5355
5356 mServiceContext.binder.restoreCallingIdentity(ident);
5357 }
5358
5359 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5360 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5361 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5362 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5363
5364 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5365 DpmMockContext.CALLER_SYSTEM_USER_UID);
5366 setUpPackageManagerForAdmin(admin1, uid);
5367 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5368 // To simulate a reboot, we just reinitialize dpms and call systemReady
5369 initializeDpms();
5370
5371 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5372 assertTrue(dpm.isAdminActive(admin1));
5373 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5374 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5375 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5376 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5377 }
5378
5379 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5380 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5381 metadataManager.deleteMetadataFile();
5382
5383 final TransferOwnershipMetadataManager.Metadata metadata =
5384 new TransferOwnershipMetadataManager.Metadata(
5385 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5386 callerUserHandle,
5387 adminType);
5388 metadataManager.saveMetadataFile(metadata);
5389 }
5390
5391 private File getDeviceOwnerFile() {
5392 return dpms.mOwners.getDeviceOwnerFile();
5393 }
5394
5395 private File getProfileOwnerFile() {
5396 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5397 }
5398
5399 private File getProfileOwnerPoliciesFile() {
5400 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5401 DpmMockContext.CALLER_USER_HANDLE);
5402 return getPoliciesFile(parentDir);
5403 }
5404
5405 private File getDeviceOwnerPoliciesFile() {
5406 return getPoliciesFile(getServices().systemUserDataDir);
5407 }
5408
5409 private File getPoliciesFile(File parentDir) {
5410 return new File(parentDir, "device_policies.xml");
5411 }
5412
5413 private InputStream getRawStream(@RawRes int id) {
5414 return mRealTestContext.getResources().openRawResource(id);
5415 }
5416
Victor Chang3e794af2016-03-04 13:48:17 +00005417 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005418 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005419 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5420 dpms.notifyChangeToContentObserver(
5421 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5422 }
5423
5424 private void assertProvisioningAllowed(String action, boolean expected) {
5425 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5426 dpm.isProvisioningAllowed(action));
5427 }
Tony Mak2f26b792016-11-28 17:54:51 +00005428
Nicolas Prevot45d29072017-01-18 16:11:19 +00005429 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5430 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005431 final String previousPackageName = mContext.packageName;
5432 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005433
5434 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5435 mContext.packageName = packageName;
5436 mMockContext.binder.callingUid = uid;
5437 assertProvisioningAllowed(action, expected);
5438
5439 // Set the previous package name / calling uid to go back to the initial state.
5440 mContext.packageName = previousPackageName;
5441 mMockContext.binder.callingUid = previousUid;
5442 }
5443
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005444 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005445 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5446 }
5447
5448 private void assertCheckProvisioningPreCondition(
5449 String action, String packageName, int provisioningCondition) {
5450 assertEquals("checkProvisioningPreCondition("
5451 + action + ", " + packageName + ") returning unexpected result",
5452 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005453 }
5454
Tony Mak2f26b792016-11-28 17:54:51 +00005455 /**
5456 * Setup a managed profile with the specified admin and its uid.
5457 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5458 * @param adminUid uid of the admin package.
5459 * @param copyFromAdmin package information for {@code admin} will be built based on this
5460 * component's information.
5461 */
5462 private void addManagedProfile(
5463 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5464 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005465 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005466 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5467 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5468 dpm.setActiveAdmin(admin, false, userId);
5469 assertTrue(dpm.setProfileOwner(admin, null, userId));
5470 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5471 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005472
5473 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005474 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005475 */
Robin Leeabaa0692017-02-20 20:54:22 +00005476 private static StringParceledListSlice asSlice(String[] s) {
5477 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005478 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005479
5480 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005481 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5482 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005483
Robin Lee2c68dad2017-03-17 12:50:24 +00005484 // We can't let exceptions happen on the background thread. Throw them here if they happen
5485 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005486 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005487 }
Victor Chang3e794af2016-03-04 13:48:17 +00005488}