blob: d90091017116567709f10e00c009cfb38d3063bc [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;
Rubin Xu19854862019-08-15 16:37:23 +010043import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010044import static org.mockito.Mockito.doAnswer;
45import static org.mockito.Mockito.doReturn;
46import static org.mockito.Mockito.never;
47import static org.mockito.Mockito.nullable;
48import static org.mockito.Mockito.reset;
49import static org.mockito.Mockito.timeout;
50import static org.mockito.Mockito.times;
51import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080052import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010053import static org.mockito.Mockito.verifyZeroInteractions;
54import static org.mockito.Mockito.when;
55import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000056import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010057
Makoto Onukif76b06a2015-09-22 15:03:44 -070058import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000059import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010061import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000062import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070063import android.app.admin.DeviceAdminReceiver;
64import android.app.admin.DevicePolicyManager;
65import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010066import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070067import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070068import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000069import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000070import android.content.pm.ApplicationInfo;
71import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070072import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010073import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000074import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000075import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010076import android.graphics.Color;
77import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080078import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070079import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080080import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070081import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070082import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010083import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080084import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010085import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000086import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000087import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000088import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080089import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010090import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092
Pavel Grafov57f1b662019-03-27 14:55:38 +000093import androidx.test.filters.SmallTest;
94
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010095import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000096import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000097import com.android.server.LocalServices;
98import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +000099import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000100import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000101
Robin Lee7f5c91c2017-02-08 21:27:02 +0000102import org.hamcrest.BaseMatcher;
103import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800104import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700105import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700106
arangelov08d534b2018-01-22 15:20:53 +0000107import java.io.File;
108import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800109import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000110import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000111import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700112import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700114import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100115import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000116import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700119 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000120 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121 m FrameworksServicesTests &&
122 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000123 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700125 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700126
127 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000128 *
129 * , or:
130 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700131 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000132@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100133@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000135 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
136 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
137 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100138 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800139 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100140 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000141
Pavel Grafov75c0a892017-05-18 17:28:27 +0100142 // TODO replace all instances of this with explicit {@link #mServiceContext}.
143 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700144 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100145
146 private DpmMockContext mServiceContext;
147 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700148 public DevicePolicyManager dpm;
149 public DevicePolicyManagerServiceTestable dpms;
150
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100151 /*
152 * The CA cert below is the content of cacert.pem as generated by:
153 *
154 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
155 */
156 private static final String TEST_CA =
157 "-----BEGIN CERTIFICATE-----\n" +
158 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
159 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
160 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
161 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
162 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
163 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
164 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
165 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
166 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
167 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
168 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
169 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
170 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
171 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
172 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
173 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
174 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
175 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
176 "wQ==\n" +
177 "-----END CERTIFICATE-----\n";
178
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700179 @Override
180 protected void setUp() throws Exception {
181 super.setUp();
182
183 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100184 mServiceContext = mContext;
185 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
186 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700187 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100188 doReturn(Collections.singletonList(new ResolveInfo()))
189 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
190 any(Intent.class),
191 anyInt(),
192 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700193
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800194 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100195 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800196
Makoto Onukia52562c2015-10-01 16:12:31 -0700197 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700198
Sudheer Shanka101c3532018-01-08 16:28:42 -0800199 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800200 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700201 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
202 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
203 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800204 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700205
Pavel Grafov75c0a892017-05-18 17:28:27 +0100206 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
207 mAdmin1Context.packageName = admin1.getPackageName();
208 mAdmin1Context.applicationInfo = new ApplicationInfo();
209 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
210
Makoto Onukib643fb02015-09-22 15:03:44 -0700211 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100212
213 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700214 }
215
arangelov08d534b2018-01-22 15:20:53 +0000216 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
217 return dpms.mTransferOwnershipMetadataManager;
218 }
219
Robin Lee2c68dad2017-03-17 12:50:24 +0000220 @Override
221 protected void tearDown() throws Exception {
222 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000223 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000224 super.tearDown();
225 }
226
Makoto Onukia52562c2015-10-01 16:12:31 -0700227 private void initializeDpms() {
228 // Need clearCallingIdentity() to pass permission checks.
229 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100230 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700231
Pavel Grafov75c0a892017-05-18 17:28:27 +0100232 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
233 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
234 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700235
Pavel Grafov75c0a892017-05-18 17:28:27 +0100236 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700237
Pavel Grafov75c0a892017-05-18 17:28:27 +0100238 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700239 }
240
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 private void setUpUserManager() {
242 // Emulate UserManager.set/getApplicationRestriction().
243 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
244
245 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000246 doAnswer((Answer<Void>) invocation -> {
247 String pkg = (String) invocation.getArguments()[0];
248 Bundle bundle = (Bundle) invocation.getArguments()[1];
249 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700250
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000251 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700252
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000253 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100254 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100255 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700256
257 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000258 doAnswer((Answer<Bundle>) invocation -> {
259 String pkg = (String) invocation.getArguments()[0];
260 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700261
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000262 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100263 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700264 anyString(), any(UserHandle.class));
265
Makoto Onukid932f762015-09-29 16:53:38 -0700266 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100267 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700268 }
269
270 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100271 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700272
Pavel Grafov75c0a892017-05-18 17:28:27 +0100273 mServiceContext.binder.callingUid =
274 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
275 runAsCaller(mServiceContext, dpms, dpm -> {
276 // PO needs to be a DA.
277 dpm.setActiveAdmin(admin, /*replace=*/ false);
278 // Fire!
279 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
280 // Check
281 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
282 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700283
Pavel Grafov75c0a892017-05-18 17:28:27 +0100284 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700285 }
286
287 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100288 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700289 .thenReturn(false);
290
291 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100292 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700293
294 // If the device has no DPMS feature, it shouldn't register the local service.
295 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
296 }
297
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800298 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800299 // Device owner in SYSTEM_USER
300 setDeviceOwner();
301 // Profile owner in CALLER_USER_HANDLE
302 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
303 setAsProfileOwner(admin2);
304 // Active admin in CALLER_USER_HANDLE
305 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
306 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
307 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
308 DpmMockContext.CALLER_USER_HANDLE);
309 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
310 DpmMockContext.CALLER_USER_HANDLE));
311
312 initializeDpms();
313
314 // Verify
315 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800316 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800317 eq(UserHandle.USER_SYSTEM));
318 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800319 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800320 adminAnotherPackage.getPackageName()),
321 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800322 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
323 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
324 }
325
326 public void testLoadAdminData_noAdmins() throws Exception {
327 final int ANOTHER_USER_ID = 15;
328 getServices().addUser(ANOTHER_USER_ID, 0);
329
330 initializeDpms();
331
332 // Verify
333 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
334 null, DpmMockContext.CALLER_USER_HANDLE);
335 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
336 null, ANOTHER_USER_ID);
337 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
338 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800339 }
340
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700341 /**
342 * Caller doesn't have proper permissions.
343 */
344 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700345 // 1. Failure cases.
346
347 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100348 assertExpectException(SecurityException.class, /* messageRegex= */ null,
349 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700350
351 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
352 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100353
354 assertExpectException(SecurityException.class, /* messageRegex= */ null,
355 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700356 }
357
Makoto Onukif76b06a2015-09-22 15:03:44 -0700358 /**
359 * Test for:
360 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800361 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700362 * {@link DevicePolicyManager#isAdminActive}
363 * {@link DevicePolicyManager#isAdminActiveAsUser}
364 * {@link DevicePolicyManager#getActiveAdmins}
365 * {@link DevicePolicyManager#getActiveAdminsAsUser}
366 */
367 public void testSetActiveAdmin() throws Exception {
368 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700369 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
370
Makoto Onukif76b06a2015-09-22 15:03:44 -0700371 // 2. Call the API.
372 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700373
374 // 3. Verify internal calls.
375
376 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700377 verify(mContext.spiedContext).sendBroadcastAsUser(
378 MockUtils.checkIntentAction(
379 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
380 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
381 verify(mContext.spiedContext).sendBroadcastAsUser(
382 MockUtils.checkIntentAction(
383 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100384 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
385 eq(null),
386 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700387
Pavel Grafov75c0a892017-05-18 17:28:27 +0100388 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700389 eq(admin1.getPackageName()),
390 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
391 eq(PackageManager.DONT_KILL_APP),
392 eq(DpmMockContext.CALLER_USER_HANDLE),
393 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700394
Sudheer Shanka101c3532018-01-08 16:28:42 -0800395 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
396 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
397
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700398 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700399
400 // Make sure it's active admin1.
401 assertTrue(dpm.isAdminActive(admin1));
402 assertFalse(dpm.isAdminActive(admin2));
403 assertFalse(dpm.isAdminActive(admin3));
404
405 // But not admin1 for a different user.
406
407 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
408 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
409 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
410
411 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
412 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
413
414 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
415
416 // Next, add one more admin.
417 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700418 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700419 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700420
421 dpm.setActiveAdmin(admin2, /* replace =*/ false);
422
423 // Now we have two admins.
424 assertTrue(dpm.isAdminActive(admin1));
425 assertTrue(dpm.isAdminActive(admin2));
426 assertFalse(dpm.isAdminActive(admin3));
427
428 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
429 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100430 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700431 eq(admin1.getPackageName()),
432 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
433 eq(PackageManager.DONT_KILL_APP),
434 eq(DpmMockContext.CALLER_USER_HANDLE),
435 anyString());
436
Sudheer Shanka101c3532018-01-08 16:28:42 -0800437 // times(2) because it was previously called for admin1 which is in the same package
438 // as admin2.
439 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
440 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
441
Makoto Onukif76b06a2015-09-22 15:03:44 -0700442 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100443 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
444 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445
446 // 5. Add the same admin1 again with replace, which should succeed.
447 dpm.setActiveAdmin(admin1, /* replace =*/ true);
448
449 // TODO make sure it's replaced.
450
451 // 6. Test getActiveAdmins()
452 List<ComponentName> admins = dpm.getActiveAdmins();
453 assertEquals(2, admins.size());
454 assertEquals(admin1, admins.get(0));
455 assertEquals(admin2, admins.get(1));
456
Sudheer Shanka101c3532018-01-08 16:28:42 -0800457 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
458 // replaced
459 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
460
Makoto Onukif76b06a2015-09-22 15:03:44 -0700461 // Another user has no admins.
462 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
463
464 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
465 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
466
467 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
468 }
469
Makoto Onukid932f762015-09-29 16:53:38 -0700470 public void testSetActiveAdmin_multiUsers() throws Exception {
471
472 final int ANOTHER_USER_ID = 100;
473 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
474
Pavel Grafov75c0a892017-05-18 17:28:27 +0100475 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700476
477 // Set up pacakge manager for the other user.
478 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
481
482 dpm.setActiveAdmin(admin1, /* replace =*/ false);
483
484 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
485 dpm.setActiveAdmin(admin2, /* replace =*/ false);
486
487
488 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
489 assertTrue(dpm.isAdminActive(admin1));
490 assertFalse(dpm.isAdminActive(admin2));
491
492 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
493 assertFalse(dpm.isAdminActive(admin1));
494 assertTrue(dpm.isAdminActive(admin2));
495 }
496
Makoto Onukif76b06a2015-09-22 15:03:44 -0700497 /**
498 * Test for:
499 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800500 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700501 */
502 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
503 // 1. Make sure the caller has proper permissions.
504 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
505
506 dpm.setActiveAdmin(admin1, /* replace =*/ false);
507 assertTrue(dpm.isAdminActive(admin1));
508
509 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100510 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
511 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700512 }
513
514 /**
515 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800516 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
517 * BIND_DEVICE_ADMIN.
518 */
519 public void testSetActiveAdmin_permissionCheck() throws Exception {
520 // 1. Make sure the caller has proper permissions.
521 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
522
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100523 assertExpectException(IllegalArgumentException.class,
524 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
525 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800526 assertFalse(dpm.isAdminActive(adminNoPerm));
527
528 // Change the target API level to MNC. Now it can be set as DA.
529 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
530 VERSION_CODES.M);
531 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
532 assertTrue(dpm.isAdminActive(adminNoPerm));
533
534 // TODO Test the "load from the file" case where DA will still be loaded even without
535 // BIND_DEVICE_ADMIN and target API is N.
536 }
537
538 /**
539 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700540 * {@link DevicePolicyManager#removeActiveAdmin}
541 */
542 public void testRemoveActiveAdmin_SecurityException() {
543 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
544
545 // Add admin.
546
547 dpm.setActiveAdmin(admin1, /* replace =*/ false);
548
549 assertTrue(dpm.isAdminActive(admin1));
550
551 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
552
553 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100554 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
555 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700556
557 // Try to remove active admin with a different caller userid should fail too, without
558 // having MANAGE_DEVICE_ADMINS.
559 mContext.callerPermissions.clear();
560
Makoto Onukid932f762015-09-29 16:53:38 -0700561 // Change the caller, and call into DPMS directly with a different user-id.
562
Makoto Onukif76b06a2015-09-22 15:03:44 -0700563 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100564 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
565 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 }
567
568 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800569 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
570 * (because we can't send the remove broadcast).
571 */
572 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
573 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
574
575 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
576
577 // Add admin.
578
579 dpm.setActiveAdmin(admin1, /* replace =*/ false);
580
581 assertTrue(dpm.isAdminActive(admin1));
582
583 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
584
585 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100586 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800587 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100588 assertExpectException(IllegalStateException.class,
589 /* messageRegex= */ "User must be running and unlocked",
590 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800591
592 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800593 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
594 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800595
596 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100597 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598 .thenReturn(true);
599
600 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700601 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800602 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
603 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800604 }
605
606 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700607 * Test for:
608 * {@link DevicePolicyManager#removeActiveAdmin}
609 */
Makoto Onukid932f762015-09-29 16:53:38 -0700610 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700611 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
612
613 // Add admin1.
614
615 dpm.setActiveAdmin(admin1, /* replace =*/ false);
616
617 assertTrue(dpm.isAdminActive(admin1));
618 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
619
620 // Different user, but should work, because caller has proper permissions.
621 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700622
623 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700624 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700627 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800628 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
629 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700630
631 // TODO DO Still can't be removed in this case.
632 }
633
634 /**
635 * Test for:
636 * {@link DevicePolicyManager#removeActiveAdmin}
637 */
638 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
639 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
640 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
641
642 // Add admin1.
643
644 dpm.setActiveAdmin(admin1, /* replace =*/ false);
645
646 assertTrue(dpm.isAdminActive(admin1));
647 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
648
649 // Broadcast from saveSettingsLocked().
650 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
651 MockUtils.checkIntentAction(
652 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
653 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
654
655 // Remove. No permissions, but same user, so it'll work.
656 mContext.callerPermissions.clear();
657 dpm.removeActiveAdmin(admin1);
658
Makoto Onukif76b06a2015-09-22 15:03:44 -0700659 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
660 MockUtils.checkIntentAction(
661 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
662 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
663 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100664 eq(AppOpsManager.OP_NONE),
665 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700666 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700667 eq(dpms.mHandler),
668 eq(Activity.RESULT_OK),
669 isNull(String.class),
670 isNull(Bundle.class));
671
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700672 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800673 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
674 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700675
676 // Again broadcast from saveSettingsLocked().
677 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
678 MockUtils.checkIntentAction(
679 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
680 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
681
682 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700683 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700684
Sudheer Shanka101c3532018-01-08 16:28:42 -0800685 public void testRemoveActiveAdmin_multipleAdminsInUser() {
686 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
687 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
688
689 // Add admin1.
690 dpm.setActiveAdmin(admin1, /* replace =*/ false);
691
692 assertTrue(dpm.isAdminActive(admin1));
693 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
694
695 // Add admin2.
696 dpm.setActiveAdmin(admin2, /* replace =*/ false);
697
698 assertTrue(dpm.isAdminActive(admin2));
699 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
700
701 // Broadcast from saveSettingsLocked().
702 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
703 MockUtils.checkIntentAction(
704 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
705 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
706
707 // Remove. No permissions, but same user, so it'll work.
708 mContext.callerPermissions.clear();
709 dpm.removeActiveAdmin(admin1);
710
711 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
712 MockUtils.checkIntentAction(
713 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
714 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
715 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100716 eq(AppOpsManager.OP_NONE),
717 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800718 any(BroadcastReceiver.class),
719 eq(dpms.mHandler),
720 eq(Activity.RESULT_OK),
721 isNull(String.class),
722 isNull(Bundle.class));
723
724 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
725 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800726 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800727 eq(DpmMockContext.CALLER_USER_HANDLE));
728
729 // Again broadcast from saveSettingsLocked().
730 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
731 MockUtils.checkIntentAction(
732 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
733 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
734 }
735
736 /**
737 * Test for:
738 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
739 */
740 public void testForceRemoveActiveAdmin() throws Exception {
741 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
742
743 // Add admin.
744 setupPackageInPackageManager(admin1.getPackageName(),
745 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
746 /* appId= */ 10138,
747 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
748 dpm.setActiveAdmin(admin1, /* replace =*/ false);
749 assertTrue(dpm.isAdminActive(admin1));
750
751 // Calling from a non-shell uid should fail with a SecurityException
752 mContext.binder.callingUid = 123456;
753 assertExpectException(SecurityException.class,
754 /* messageRegex =*/ "Non-shell user attempted to call",
755 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
756
757 mContext.binder.callingUid = Process.SHELL_UID;
758 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
759
760 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
761 // Verify
762 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
763 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
764 null, DpmMockContext.CALLER_USER_HANDLE);
765 }
766
Makoto Onukib643fb02015-09-22 15:03:44 -0700767 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100768 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
769 *
770 * Validates that when the password history length is set, it is persisted after rebooting
771 */
772 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
773 int passwordHistoryLength = 2;
774
775 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
776 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
777 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
778
779 // Install admin1 on system user.
780 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
781
782 // Set admin1 to active admin and device owner
783 dpm.setActiveAdmin(admin1, false);
784 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
785
786 // Save password history length
787 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
788
789 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
790
791 initializeDpms();
792 reset(mContext.spiedContext);
793
794 // Password history length should persist after rebooted
795 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
796 }
797
798 /**
799 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000800 *
801 * Validates that when the password for a user changes, the notification broadcast intent
802 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
803 * addition to ones in the original user.
804 */
805 public void testSetActivePasswordState_sendToProfiles() throws Exception {
806 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
807
808 final int MANAGED_PROFILE_USER_ID = 78;
809 final int MANAGED_PROFILE_ADMIN_UID =
810 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
811
812 // Setup device owner.
813 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
814 mContext.packageName = admin1.getPackageName();
815 setupDeviceOwner();
816
817 // Add a managed profile belonging to the system user.
818 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
819
820 // Change the parent user's password.
821 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
822
823 // Both the device owner and the managed profile owner should receive this broadcast.
824 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
825 intent.setComponent(admin1);
826 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
827
828 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
829 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100830 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
831 eq(null),
832 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000833 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
834 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100835 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
836 eq(null),
837 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000838 }
839
840 /**
Rubin Xu19854862019-08-15 16:37:23 +0100841 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000842 *
843 * Validates that when the password for a managed profile changes, the notification broadcast
844 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
845 * its parent.
846 */
847 public void testSetActivePasswordState_notSentToParent() throws Exception {
848 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
849
850 final int MANAGED_PROFILE_USER_ID = 78;
851 final int MANAGED_PROFILE_ADMIN_UID =
852 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
853
854 // Setup device owner.
855 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
856 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100857 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000858 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
859 setupDeviceOwner();
860
861 // Add a managed profile belonging to the system user.
862 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
863
864 // Change the profile's password.
865 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
866
867 // Both the device owner and the managed profile owner should receive this broadcast.
868 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
869 intent.setComponent(admin1);
870 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
871
872 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
873 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100874 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
875 eq(null),
876 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000877 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
878 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100879 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
880 eq(null),
881 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000882 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100883
Robin Leed2a73ed2016-12-19 09:07:16 +0000884 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000885 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700886 */
887 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000888 setDeviceOwner();
889
890 // Try to set a profile owner on the same user, which should fail.
891 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
892 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100893 assertExpectException(IllegalStateException.class,
894 /* messageRegex= */ "already has a device owner",
895 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000896
897 // DO admin can't be deactivated.
898 dpm.removeActiveAdmin(admin1);
899 assertTrue(dpm.isAdminActive(admin1));
900
901 // TODO Test getDeviceOwnerName() too. To do so, we need to change
902 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
903 }
904
905 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700906 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800907 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700908 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
909 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
910
Makoto Onukid932f762015-09-29 16:53:38 -0700911 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700912 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
913
Makoto Onukid932f762015-09-29 16:53:38 -0700914 // Make sure admin1 is installed on system user.
915 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700916
Makoto Onukic8a5a552015-11-19 14:29:12 -0800917 // Check various get APIs.
918 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
919
Makoto Onukib643fb02015-09-22 15:03:44 -0700920 // DO needs to be an DA.
921 dpm.setActiveAdmin(admin1, /* replace =*/ false);
922
923 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700924 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700925
Makoto Onukic8a5a552015-11-19 14:29:12 -0800926 // getDeviceOwnerComponent should return the admin1 component.
927 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
928 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
929
930 // Check various get APIs.
931 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
932
933 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
934 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
935 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
936 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
937
938 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
939
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000940 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100941 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000942 eq(admin1.getPackageName()));
943
Makoto Onukib643fb02015-09-22 15:03:44 -0700944 // TODO We should check if the caller has called clearCallerIdentity().
Pavel Grafov75c0a892017-05-18 17:28:27 +0100945 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
Makoto Onukib643fb02015-09-22 15:03:44 -0700946 eq(UserHandle.USER_SYSTEM), eq(false));
947
948 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
949 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
950 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
951
Makoto Onukic8a5a552015-11-19 14:29:12 -0800952 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700953 }
954
Makoto Onukic8a5a552015-11-19 14:29:12 -0800955 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
956 final int origCallingUser = mContext.binder.callingUid;
957 final List origPermissions = new ArrayList(mContext.callerPermissions);
958 mContext.callerPermissions.clear();
959
960 mContext.callerPermissions.add(permission.MANAGE_USERS);
961
962 mContext.binder.callingUid = Process.SYSTEM_UID;
963
964 // TODO Test getDeviceOwnerName() too. To do so, we need to change
965 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
966 if (hasDeviceOwner) {
967 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
968 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
969 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
970
971 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
972 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
973 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
974 } else {
975 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
976 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
977 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
978
979 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
980 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
981 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
982 }
983
984 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
985 if (hasDeviceOwner) {
986 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
987 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
988 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
989
990 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
991 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
992 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
993 } else {
994 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
995 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
996 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
997
998 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
999 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1000 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1001 }
1002
1003 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1004 // Still with MANAGE_USERS.
1005 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1006 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1007 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1008
1009 if (hasDeviceOwner) {
1010 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1011 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1012 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1013 } else {
1014 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1015 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1016 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1017 }
1018
1019 mContext.binder.callingUid = Process.SYSTEM_UID;
1020 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1021 // System can still call "OnAnyUser" without MANAGE_USERS.
1022 if (hasDeviceOwner) {
1023 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1024 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1025 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1026
1027 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1028 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1029 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1030 } else {
1031 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1032 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1033 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1034
1035 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1036 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1037 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1038 }
1039
1040 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1041 // Still no MANAGE_USERS.
1042 if (hasDeviceOwner) {
1043 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1044 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1045 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1046 } else {
1047 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1048 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1049 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1050 }
1051
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001052 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1053 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1054 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1055 dpm::getDeviceOwnerComponentOnAnyUser);
1056 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1057 dpm::getDeviceOwnerUserId);
1058 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1059 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001060
1061 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1062 // Still no MANAGE_USERS.
1063 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1064 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1065 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1066
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001067 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1068 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1069 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1070 dpm::getDeviceOwnerComponentOnAnyUser);
1071 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1072 dpm::getDeviceOwnerUserId);
1073 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1074 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001075
1076 // Restore.
1077 mContext.binder.callingUid = origCallingUser;
1078 mContext.callerPermissions.addAll(origPermissions);
1079 }
1080
1081
Makoto Onukib643fb02015-09-22 15:03:44 -07001082 /**
1083 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1084 */
1085 public void testSetDeviceOwner_noSuchPackage() {
1086 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001087 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001088 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1089 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1090
1091 // Call from a process on the system user.
1092 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1093
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001094 assertExpectException(IllegalArgumentException.class,
1095 /* messageRegex= */ "Invalid component",
1096 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001097 }
1098
1099 public void testSetDeviceOwner_failures() throws Exception {
1100 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1101 }
1102
Makoto Onukia52562c2015-10-01 16:12:31 -07001103 public void testClearDeviceOwner() throws Exception {
1104 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001105 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001106 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1107 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1108
1109 // Set admin1 as a DA to the secondary user.
1110 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1111
1112 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1113
1114 // Set admin 1 as the DO to the system user.
1115
1116 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1117 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1118 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1119 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1120
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001121 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001122 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001123 eq(admin1.getPackageName()));
1124
Makoto Onukic8a5a552015-11-19 14:29:12 -08001125 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001126
Makoto Onuki90b89652016-01-28 14:44:18 -08001127 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001128 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001129 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001130
1131 assertTrue(dpm.isAdminActive(admin1));
1132 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1133
Makoto Onukia52562c2015-10-01 16:12:31 -07001134 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001135 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001136
1137 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001138 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1139 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001140
1141 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001142 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001143 assertExpectException(IllegalStateException.class,
1144 /* messageRegex= */ "User must be running and unlocked",
1145 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001146
Pavel Grafov75c0a892017-05-18 17:28:27 +01001147 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1148 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001149 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1150
1151 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001152 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001153
Pavel Grafov75c0a892017-05-18 17:28:27 +01001154 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001155 eq(false),
1156 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1157
Pavel Grafov75c0a892017-05-18 17:28:27 +01001158 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001159 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001160 eq(null),
1161 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001162
Sudheer Shanka101c3532018-01-08 16:28:42 -08001163 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1164 null, UserHandle.USER_SYSTEM);
1165
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001166 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001167
1168 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1169 // and once for clearing it.
1170 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1171 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1172 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001173 // TODO Check other calls.
1174 }
1175
1176 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1177 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001178 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001179 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1180 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1181
1182 // Set admin1 as a DA to the secondary user.
1183 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1184
1185 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1186
1187 // Set admin 1 as the DO to the system user.
1188
1189 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1190 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1191 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1192 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1193
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001194 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001195 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001196 eq(admin1.getPackageName()));
1197
Makoto Onukic8a5a552015-11-19 14:29:12 -08001198 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001199
1200 // Now call clear from the secondary user, which should throw.
1201 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1202
1203 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001204 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001205 eq(admin1.getPackageName()),
1206 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001207 assertExpectException(SecurityException.class,
1208 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1209 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001210
Makoto Onukic8a5a552015-11-19 14:29:12 -08001211 // DO shouldn't be removed.
1212 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001213 }
1214
Makoto Onukib643fb02015-09-22 15:03:44 -07001215 public void testSetProfileOwner() throws Exception {
1216 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001217
Makoto Onuki90b89652016-01-28 14:44:18 -08001218 // PO admin can't be deactivated.
1219 dpm.removeActiveAdmin(admin1);
1220 assertTrue(dpm.isAdminActive(admin1));
1221
Makoto Onuki803d6752015-10-30 12:58:39 -07001222 // Try setting DO on the same user, which should fail.
1223 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001224 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1225 runAsCaller(mServiceContext, dpms, dpm -> {
1226 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001227 assertExpectException(IllegalStateException.class,
1228 /* messageRegex= */ "already has a profile owner",
1229 () -> dpm.setDeviceOwner(admin2, "owner-name",
1230 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001231 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001232 }
1233
Makoto Onuki90b89652016-01-28 14:44:18 -08001234 public void testClearProfileOwner() throws Exception {
1235 setAsProfileOwner(admin1);
1236
1237 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1238
1239 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1240 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1241
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001242 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001243 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001244 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001245 assertExpectException(IllegalStateException.class,
1246 /* messageRegex= */ "User must be running and unlocked",
1247 () -> dpm.clearProfileOwner(admin1));
1248
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001249 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001250 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001251 dpm.clearProfileOwner(admin1);
1252
1253 // Check
1254 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001255 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001256 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1257 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001258 }
1259
Makoto Onukib643fb02015-09-22 15:03:44 -07001260 public void testSetProfileOwner_failures() throws Exception {
1261 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1262 }
1263
Makoto Onukia52562c2015-10-01 16:12:31 -07001264 public void testGetDeviceOwnerAdminLocked() throws Exception {
1265 checkDeviceOwnerWithMultipleDeviceAdmins();
1266 }
1267
1268 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1269 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1270 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1271 // make sure it gets the right component from the right user.
1272
1273 final int ANOTHER_USER_ID = 100;
1274 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1275
Pavel Grafov75c0a892017-05-18 17:28:27 +01001276 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001277
1278 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001279 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001280 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1281 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1282
1283 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1284
Pavel Grafov75c0a892017-05-18 17:28:27 +01001285 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001286
Makoto Onukia52562c2015-10-01 16:12:31 -07001287 // Make sure the admin packge is installed to each user.
1288 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1289 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1290
1291 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1292 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1293
1294 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1295
1296
1297 // Set active admins to the users.
1298 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1299 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1300
1301 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1302 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1303
1304 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1305
1306 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001307 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001308 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1309
Makoto Onukic8a5a552015-11-19 14:29:12 -08001310 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001311
1312 // Then check getDeviceOwnerAdminLocked().
1313 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1314 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1315 }
1316
1317 /**
1318 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001319 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1320 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001321 *
1322 * We didn't use to persist the DO component class name, but now we do, and the above method
1323 * finds the right component from a package name upon migration.
1324 */
1325 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001326 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001327 checkDeviceOwnerWithMultipleDeviceAdmins();
1328
1329 // Overwrite the device owner setting and clears the clas name.
1330 dpms.mOwners.setDeviceOwner(
1331 new ComponentName(admin2.getPackageName(), ""),
1332 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1333 dpms.mOwners.writeDeviceOwner();
1334
1335 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001336 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001337
1338 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001339 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001340 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001341 initializeDpms();
1342
1343 // Now the DO component name is a full name.
1344 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1345 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001346 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001347 }
1348
Makoto Onukib643fb02015-09-22 15:03:44 -07001349 public void testSetGetApplicationRestriction() {
1350 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001351 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001352
1353 {
1354 Bundle rest = new Bundle();
1355 rest.putString("KEY_STRING", "Foo1");
1356 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1357 }
1358
1359 {
1360 Bundle rest = new Bundle();
1361 rest.putString("KEY_STRING", "Foo2");
1362 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1363 }
1364
1365 {
1366 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1367 assertNotNull(returned);
1368 assertEquals(returned.size(), 1);
1369 assertEquals(returned.get("KEY_STRING"), "Foo1");
1370 }
1371
1372 {
1373 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1374 assertNotNull(returned);
1375 assertEquals(returned.size(), 1);
1376 assertEquals(returned.get("KEY_STRING"), "Foo2");
1377 }
1378
1379 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1380 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1381 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001382
Edman Anjosf9946772016-11-28 16:35:15 +01001383 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001384 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1385 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001386 *
1387 * @param packageName the name of the package to be setup
1388 * @param appId the application ID to be given to the package
1389 * @return the UID of the package as known by the mock package manager
1390 */
1391 private int setupPackageInPackageManager(final String packageName, final int appId)
1392 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001393 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001394 ApplicationInfo.FLAG_HAS_CODE);
1395 }
1396
1397 /**
1398 * Setup a package in the package manager mock. Useful for faking installed applications.
1399 *
1400 * @param packageName the name of the package to be setup
1401 * @param userId the user id where the package will be "installed"
1402 * @param appId the application ID to be given to the package
1403 * @param flags flags to set in the ApplicationInfo for this package
1404 * @return the UID of the package as known by the mock package manager
1405 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001406 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1407 int flags) throws Exception {
1408 final int uid = UserHandle.getUid(userId, appId);
1409 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001410 final PackageInfo pi = new PackageInfo();
1411 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001412 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001413 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001414 eq(packageName),
1415 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001416 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001417 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001418 eq(packageName),
1419 anyInt(),
1420 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001421 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001422 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001423 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001424 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001425 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001426 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001427 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001428 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001429 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001430 return uid;
1431 }
1432
Robin Lee7f5c91c2017-02-08 21:27:02 +00001433 public void testCertificateDisclosure() throws Exception {
1434 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1435 final UserHandle user = UserHandle.of(userId);
1436
1437 mContext.applicationInfo = new ApplicationInfo();
1438 mContext.callerPermissions.add(permission.MANAGE_USERS);
1439 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001440 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001441 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1442
Robin Leeabaa0692017-02-20 20:54:22 +00001443 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1444 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001445
1446 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1447 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1448
1449 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001450 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001451 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001452 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001453 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001454 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001455 .cancelAsUser(anyString(), anyInt(), eq(user));
1456
1457 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001458 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001459 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001460 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1461 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001462 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001463 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001464 .notifyAsUser(anyString(), anyInt(), argThat(
1465 new BaseMatcher<Notification>() {
1466 @Override
1467 public boolean matches(Object item) {
1468 final Notification noti = (Notification) item;
1469 return TEST_STRING.equals(
1470 noti.extras.getString(Notification.EXTRA_TITLE));
1471 }
1472 @Override
1473 public void describeTo(Description description) {
1474 description.appendText(
1475 "Notification{title=\"" + TEST_STRING + "\"}");
1476 }
1477 }), eq(user));
1478 }
1479
Edman Anjosf9946772016-11-28 16:35:15 +01001480 /**
1481 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1482 * privileges can acually be exercised by a delegate are not covered here.
1483 */
1484 public void testDelegation() throws Exception {
1485 setAsProfileOwner(admin1);
1486
1487 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1488
1489 // Given two packages
1490 final String CERT_DELEGATE = "com.delegate.certs";
1491 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1492 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1493 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1494 20989);
1495
1496 // On delegation
1497 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1498 mContext.packageName = admin1.getPackageName();
1499 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1500 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1501
1502 // DPMS correctly stores and retrieves the delegates
1503 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1504 assertEquals(2, policy.mDelegationMap.size());
1505 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1506 DELEGATION_CERT_INSTALL);
1507 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1508 DELEGATION_CERT_INSTALL);
1509 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1510 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1511 DELEGATION_APP_RESTRICTIONS);
1512 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1513 DELEGATION_APP_RESTRICTIONS);
1514 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1515
1516 // On calling install certificate APIs from an unauthorized process
1517 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1518 mContext.packageName = RESTRICTIONS_DELEGATE;
1519
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001520 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1521 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001522
1523 // On calling install certificate APIs from an authorized process
1524 mContext.binder.callingUid = CERT_DELEGATE_UID;
1525 mContext.packageName = CERT_DELEGATE;
1526
1527 // DPMS executes without a SecurityException
1528 try {
1529 dpm.installCaCert(null, null);
1530 } catch (SecurityException unexpected) {
1531 fail("Threw SecurityException on authorized access");
1532 } catch (NullPointerException expected) {
1533 }
1534
1535 // On removing a delegate
1536 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1537 mContext.packageName = admin1.getPackageName();
1538 dpm.setCertInstallerPackage(admin1, null);
1539
1540 // DPMS does not allow access to ex-delegate
1541 mContext.binder.callingUid = CERT_DELEGATE_UID;
1542 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001543 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1544 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001545
1546 // But still allows access to other existing delegates
1547 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1548 mContext.packageName = RESTRICTIONS_DELEGATE;
1549 try {
1550 dpm.getApplicationRestrictions(null, "pkg");
1551 } catch (SecurityException expected) {
1552 fail("Threw SecurityException on authorized access");
1553 }
1554 }
1555
Esteban Talaverabf60f722015-12-10 16:26:44 +00001556 public void testApplicationRestrictionsManagingApp() throws Exception {
1557 setAsProfileOwner(admin1);
1558
Rubin Xued1928a2016-02-11 17:23:06 +00001559 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001560 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001561 final String nonDelegateExceptionMessageRegex =
1562 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001563 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001564 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1565 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001566
Esteban Talaverabf60f722015-12-10 16:26:44 +00001567 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1568 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001569 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1570 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001571 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001572 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001573 rest.putString("KEY_STRING", "Foo1");
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 // Check via the profile owner that no restrictions were set.
1578 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001579 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001580 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1581
Rubin Xued1928a2016-02-11 17:23:06 +00001582 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001583 assertExpectException(PackageManager.NameNotFoundException.class,
1584 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1585 () -> dpm.setApplicationRestrictionsManagingPackage(
1586 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001587
Esteban Talaverabf60f722015-12-10 16:26:44 +00001588 // Let appRestrictionsManagerPackage manage app restrictions
1589 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1590 assertEquals(appRestrictionsManagerPackage,
1591 dpm.getApplicationRestrictionsManagingPackage(admin1));
1592
1593 // Now that package should be able to set and retrieve app restrictions.
1594 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001595 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001596 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1597 dpm.setApplicationRestrictions(null, "pkg1", rest);
1598 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1599 assertEquals(1, returned.size(), 1);
1600 assertEquals("Foo1", returned.get("KEY_STRING"));
1601
1602 // The same app running on a separate user shouldn't be able to manage app restrictions.
1603 mContext.binder.callingUid = UserHandle.getUid(
1604 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1605 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001606 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1607 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001608
1609 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1610 // too.
1611 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001612 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001613 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1614 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1615 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1616
1617 // Removing the ability for the package to manage app restrictions.
1618 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1619 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1620 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001621 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001622 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001623 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1624 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001625 }
1626
Makoto Onukia4f11972015-10-01 13:19:58 -07001627 public void testSetUserRestriction_asDo() throws Exception {
1628 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001629 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001630 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1631 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1632
1633 // First, set DO.
1634
1635 // Call from a process on the system user.
1636 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1637
1638 // Make sure admin1 is installed on system user.
1639 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001640
1641 // Call.
1642 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001643 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001644 UserHandle.USER_SYSTEM));
1645
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001646 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001647 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001648 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001649 DpmTestUtils.assertRestrictions(
1650 DpmTestUtils.newRestrictions(defaultRestrictions),
1651 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1652 );
1653 DpmTestUtils.assertRestrictions(
1654 DpmTestUtils.newRestrictions(defaultRestrictions),
1655 dpm.getUserRestrictions(admin1)
1656 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001657 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001658 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001659 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001660 eq(true) /* isDeviceOwner */,
1661 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001662 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001663 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001664
1665 for (String restriction : defaultRestrictions) {
1666 dpm.clearUserRestriction(admin1, restriction);
1667 }
1668
Esteban Talavera548a04b2016-12-20 15:22:30 +00001669 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001670 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671
1672 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001673 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001675 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1676 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001677 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678
Makoto Onukia4f11972015-10-01 13:19:58 -07001679 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001680 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001681 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001682 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1683 UserManager.DISALLOW_ADD_USER),
1684 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001685 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001686
Makoto Onuki068c54a2015-10-13 14:34:03 -07001687 DpmTestUtils.assertRestrictions(
1688 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001689 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001690 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1691 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001692 DpmTestUtils.assertRestrictions(
1693 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001694 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001695 dpm.getUserRestrictions(admin1)
1696 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001697
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001699 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001700 eq(UserHandle.USER_SYSTEM),
1701 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001702 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001703 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001704
Makoto Onuki068c54a2015-10-13 14:34:03 -07001705 DpmTestUtils.assertRestrictions(
1706 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1707 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1708 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001709 DpmTestUtils.assertRestrictions(
1710 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1711 dpm.getUserRestrictions(admin1)
1712 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001713
1714 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001715 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001716 eq(UserHandle.USER_SYSTEM),
1717 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001718 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001719 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001720
Esteban Talavera548a04b2016-12-20 15:22:30 +00001721 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001722
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1724 // DO sets them, the scope is global.
1725 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001726 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001728 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001729 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001730 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001731 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1732 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001733 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001734
1735 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1736 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001737 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001738
1739 // More tests.
1740 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001741 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001742 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001743 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1744 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001745 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001746
1747 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001748 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001749 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001750 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001751 UserManager.DISALLOW_ADD_USER),
1752 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001753 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001754
1755 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001756 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001757 eq(UserHandle.USER_SYSTEM),
1758 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001759 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001760 UserManager.DISALLOW_ADD_USER),
1761 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001762 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001763 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001764
Eric Sandnessca5969d2018-08-10 13:28:46 +01001765 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1766 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1767 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001768
Eric Sandnessca5969d2018-08-10 13:28:46 +01001769 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1770 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001771
Eric Sandnessca5969d2018-08-10 13:28:46 +01001772 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1773 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1774 () -> dpm.setCameraDisabled(admin1, true));
1775 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1776
1777 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1778 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1779 () -> dpm.setKeyguardDisabledFeatures(admin1,
1780 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1781 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1782
1783 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1784 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1785 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1786 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1787
1788 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1789 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1790 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1791 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001792 }
1793
1794 public void testSetUserRestriction_asPo() {
1795 setAsProfileOwner(admin1);
1796
Makoto Onuki068c54a2015-10-13 14:34:03 -07001797 DpmTestUtils.assertRestrictions(
1798 DpmTestUtils.newRestrictions(),
1799 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1800 .ensureUserRestrictions()
1801 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001802
1803 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001804 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001805 eq(DpmMockContext.CALLER_USER_HANDLE),
1806 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001807 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001808 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001809
Makoto Onukia4f11972015-10-01 13:19:58 -07001810 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001811 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001812 eq(DpmMockContext.CALLER_USER_HANDLE),
1813 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1814 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001815 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001816 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001817
Makoto Onuki068c54a2015-10-13 14:34:03 -07001818 DpmTestUtils.assertRestrictions(
1819 DpmTestUtils.newRestrictions(
1820 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1821 UserManager.DISALLOW_OUTGOING_CALLS
1822 ),
1823 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1824 .ensureUserRestrictions()
1825 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001826 DpmTestUtils.assertRestrictions(
1827 DpmTestUtils.newRestrictions(
1828 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1829 UserManager.DISALLOW_OUTGOING_CALLS
1830 ),
1831 dpm.getUserRestrictions(admin1)
1832 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001833
1834 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001835 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001836 eq(DpmMockContext.CALLER_USER_HANDLE),
1837 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001838 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001839 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001840
1841 DpmTestUtils.assertRestrictions(
1842 DpmTestUtils.newRestrictions(
1843 UserManager.DISALLOW_OUTGOING_CALLS
1844 ),
1845 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1846 .ensureUserRestrictions()
1847 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001848 DpmTestUtils.assertRestrictions(
1849 DpmTestUtils.newRestrictions(
1850 UserManager.DISALLOW_OUTGOING_CALLS
1851 ),
1852 dpm.getUserRestrictions(admin1)
1853 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001854
1855 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001856 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001857 eq(DpmMockContext.CALLER_USER_HANDLE),
1858 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001859 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001860 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001861
Makoto Onuki068c54a2015-10-13 14:34:03 -07001862 DpmTestUtils.assertRestrictions(
1863 DpmTestUtils.newRestrictions(),
1864 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1865 .ensureUserRestrictions()
1866 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001867 DpmTestUtils.assertRestrictions(
1868 DpmTestUtils.newRestrictions(),
1869 dpm.getUserRestrictions(admin1)
1870 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001871
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001872 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1873 // though when DO sets them they'll be applied globally.
1874 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001875 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001876 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001877 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001878 eq(DpmMockContext.CALLER_USER_HANDLE),
1879 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1880 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001881 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001882 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001883
1884 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001885 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001886 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001887 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001888 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001889 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001890 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001891
Makoto Onukia4f11972015-10-01 13:19:58 -07001892 // TODO Make sure restrictions are written to the file.
1893 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001894
Esteban Talavera548a04b2016-12-20 15:22:30 +00001895
1896 public void testDefaultEnabledUserRestrictions() throws Exception {
1897 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1898 mContext.callerPermissions.add(permission.MANAGE_USERS);
1899 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1900 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1901
1902 // First, set DO.
1903
1904 // Call from a process on the system user.
1905 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1906
1907 // Make sure admin1 is installed on system user.
1908 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1909
1910 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1911 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1912 UserHandle.USER_SYSTEM));
1913
1914 // Check that the user restrictions that are enabled by default are set. Then unset them.
1915 String[] defaultRestrictions = UserRestrictionsUtils
1916 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1917 assertTrue(defaultRestrictions.length > 0);
1918 DpmTestUtils.assertRestrictions(
1919 DpmTestUtils.newRestrictions(defaultRestrictions),
1920 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1921 );
1922 DpmTestUtils.assertRestrictions(
1923 DpmTestUtils.newRestrictions(defaultRestrictions),
1924 dpm.getUserRestrictions(admin1)
1925 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001926 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001927 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001928 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001929 eq(true) /* isDeviceOwner */,
1930 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001931 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001932 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001933
1934 for (String restriction : defaultRestrictions) {
1935 dpm.clearUserRestriction(admin1, restriction);
1936 }
1937
1938 assertNoDeviceOwnerRestrictions();
1939
1940 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001941 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001942 initializeDpms();
1943 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1944 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1945
1946 assertNoDeviceOwnerRestrictions();
1947
1948 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1949 // is set as it wasn't enabled during setDeviceOwner.
1950 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1951 assertFalse(UserRestrictionsUtils
1952 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1953 UserRestrictionsUtils
1954 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1955 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001956 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001957 initializeDpms();
1958 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1959 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1960
1961 DpmTestUtils.assertRestrictions(
1962 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1963 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1964 );
1965 DpmTestUtils.assertRestrictions(
1966 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1967 dpm.getUserRestrictions(admin1)
1968 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001969 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001970 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001971 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001972 eq(true) /* isDeviceOwner */,
1973 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001974 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001975 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00001976
1977 // Remove the restriction.
1978 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1979
1980 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1981 initializeDpms();
1982 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1983 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1984 assertNoDeviceOwnerRestrictions();
1985 } finally {
1986 UserRestrictionsUtils
1987 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1988 }
1989 }
1990
1991 private void assertNoDeviceOwnerRestrictions() {
1992 DpmTestUtils.assertRestrictions(
1993 DpmTestUtils.newRestrictions(),
1994 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1995 );
1996 DpmTestUtils.assertRestrictions(
1997 DpmTestUtils.newRestrictions(),
1998 dpm.getUserRestrictions(admin1)
1999 );
2000 }
2001
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002002 public void testGetMacAddress() throws Exception {
2003 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2004 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2005 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2006
2007 // In this test, change the caller user to "system".
2008 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2009
2010 // Make sure admin1 is installed on system user.
2011 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2012
2013 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002014 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2015 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002016
2017 // DO needs to be an DA.
2018 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2019 assertTrue(dpm.isAdminActive(admin1));
2020
2021 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002022 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2023 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002024
2025 // Test 3. Caller has PO, but not DO.
2026 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002027 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2028 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002029
2030 // Remove PO.
2031 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002032 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002033 // Test 4, Caller is DO now.
2034 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2035
xshu425b9a62018-12-13 14:18:18 -08002036 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002037 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002038
xshu425b9a62018-12-13 14:18:18 -08002039 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2040 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002041 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002042
2043 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002044 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2045 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002046 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002047 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002048
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002049 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002050 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2051 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2052
2053 // In this test, change the caller user to "system".
2054 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2055
2056 // Make sure admin1 is installed on system user.
2057 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2058
2059 // Set admin1 as DA.
2060 dpm.setActiveAdmin(admin1, false);
2061 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002062 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2063 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002064
2065 // Set admin1 as PO.
2066 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002067 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2068 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002069
2070 // Remove PO and add DO.
2071 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002072 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002073 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2074
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002075 // admin1 is DO.
2076 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002077 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002078 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002079 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2080 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002081
2082 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002083 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002084 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002085 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2086 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002087
2088 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002089 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002090 dpm.reboot(admin1);
2091 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002092
2093 public void testSetGetSupportText() {
2094 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2095 dpm.setActiveAdmin(admin1, true);
2096 dpm.setActiveAdmin(admin2, true);
2097 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2098
2099 // Null default support messages.
2100 {
2101 assertNull(dpm.getLongSupportMessage(admin1));
2102 assertNull(dpm.getShortSupportMessage(admin1));
2103 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2104 assertNull(dpm.getShortSupportMessageForUser(admin1,
2105 DpmMockContext.CALLER_USER_HANDLE));
2106 assertNull(dpm.getLongSupportMessageForUser(admin1,
2107 DpmMockContext.CALLER_USER_HANDLE));
2108 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2109 }
2110
2111 // Only system can call the per user versions.
2112 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002113 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2114 () -> dpm.getShortSupportMessageForUser(admin1,
2115 DpmMockContext.CALLER_USER_HANDLE));
2116 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2117 () -> dpm.getLongSupportMessageForUser(admin1,
2118 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002119 }
2120
2121 // Can't set message for admin in another uid.
2122 {
2123 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002124 assertExpectException(SecurityException.class,
2125 /* messageRegex= */ "is not owned by uid",
2126 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002127 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2128 }
2129
2130 // Set/Get short returns what it sets and other admins text isn't changed.
2131 {
2132 final String supportText = "Some text to test with.";
2133 dpm.setShortSupportMessage(admin1, supportText);
2134 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2135 assertNull(dpm.getLongSupportMessage(admin1));
2136 assertNull(dpm.getShortSupportMessage(admin2));
2137
2138 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2139 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2140 DpmMockContext.CALLER_USER_HANDLE));
2141 assertNull(dpm.getShortSupportMessageForUser(admin2,
2142 DpmMockContext.CALLER_USER_HANDLE));
2143 assertNull(dpm.getLongSupportMessageForUser(admin1,
2144 DpmMockContext.CALLER_USER_HANDLE));
2145 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2146
2147 dpm.setShortSupportMessage(admin1, null);
2148 assertNull(dpm.getShortSupportMessage(admin1));
2149 }
2150
2151 // Set/Get long returns what it sets and other admins text isn't changed.
2152 {
2153 final String supportText = "Some text to test with.\nWith more text.";
2154 dpm.setLongSupportMessage(admin1, supportText);
2155 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2156 assertNull(dpm.getShortSupportMessage(admin1));
2157 assertNull(dpm.getLongSupportMessage(admin2));
2158
2159 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2160 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2161 DpmMockContext.CALLER_USER_HANDLE));
2162 assertNull(dpm.getLongSupportMessageForUser(admin2,
2163 DpmMockContext.CALLER_USER_HANDLE));
2164 assertNull(dpm.getShortSupportMessageForUser(admin1,
2165 DpmMockContext.CALLER_USER_HANDLE));
2166 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2167
2168 dpm.setLongSupportMessage(admin1, null);
2169 assertNull(dpm.getLongSupportMessage(admin1));
2170 }
2171 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002172
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002173 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002174 setAsProfileOwner(admin1);
2175
2176 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002177 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002178
2179 // Setup
2180 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2181 final String package1 = "com.example.one";
2182 final String package2 = "com.example.two";
2183 pkgsToRestrict.add(package1);
2184 pkgsToRestrict.add(package2);
2185 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2186 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002187 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002188
2189 // Verify
2190 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002191 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002192 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2193 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2194 eq(DpmMockContext.CALLER_USER_HANDLE));
2195
2196 // Setup
2197 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002198 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002199
2200 // Verify
2201 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002202 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002203 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2204 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2205 eq(DpmMockContext.CALLER_USER_HANDLE));
2206 }
2207
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002208 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002209 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2210 dpm.setActiveAdmin(admin1, true);
2211 assertTrue(dpm.isAdminActive(admin1));
2212 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2213
2214 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002215 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002216 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002217 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002218 }
2219
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002220 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002221 setAsProfileOwner(admin1);
2222
2223 // Setup
2224 final ArrayList<String> emptyList = new ArrayList<>();
2225 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2226 final String package1 = "com.example.one";
2227 final String package2 = "com.example.two";
2228 final String package3 = "com.example.three";
2229 pkgsToRestrict.add(package1);
2230 pkgsToRestrict.add(package2);
2231 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2232 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002233 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002234
2235 // Verify
2236 assertEquals(emptyList, excludedPkgs);
2237 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2238 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002239 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002240 DpmMockContext.CALLER_USER_HANDLE));
2241 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002242 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002243 DpmMockContext.CALLER_USER_HANDLE));
2244 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002245 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002246 DpmMockContext.CALLER_USER_HANDLE));
2247 }
2248
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002249 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002250 setAsProfileOwner(admin1);
2251 assertExpectException(SecurityException.class,
2252 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002253 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002254 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2255 dpm.clearProfileOwner(admin1);
2256
2257 setDeviceOwner();
2258 assertExpectException(SecurityException.class,
2259 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002260 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002261 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2262 clearDeviceOwner();
2263 }
2264
phweiss73145f42017-01-17 19:06:38 +01002265 public void testCreateAdminSupportIntent() throws Exception {
2266 // Setup device owner.
2267 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2268 setupDeviceOwner();
2269
2270 // Nonexisting permission returns null
2271 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2272 assertNull(intent);
2273
2274 // Existing permission that is not set returns null
2275 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2276 assertNull(intent);
2277
2278 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002279 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002280 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2281 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2282 .thenReturn(true);
2283 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2284 assertNull(intent);
2285
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002286 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2287 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2288 new UserManager.EnforcingUser(
2289 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2290 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002291 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002292 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002293 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2294 assertNotNull(intent);
2295 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2296 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2297 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002298 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002299 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2300 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2301
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002302 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2303 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002304
2305 // Camera is not disabled
2306 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2307 assertNull(intent);
2308
2309 // Camera is disabled
2310 dpm.setCameraDisabled(admin1, true);
2311 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2312 assertNotNull(intent);
2313 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2314 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2315
2316 // Screen capture is not disabled
2317 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2318 assertNull(intent);
2319
2320 // Screen capture is disabled
2321 dpm.setScreenCaptureDisabled(admin1, true);
2322 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2323 assertNotNull(intent);
2324 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2325 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2326
2327 // Same checks for different user
2328 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2329 // Camera should be disabled by device owner
2330 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2331 assertNotNull(intent);
2332 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2333 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2334 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2335 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2336 // ScreenCapture should not be disabled by device owner
2337 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2338 assertNull(intent);
2339 }
2340
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002341 /**
2342 * Test for:
2343 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002344 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002345 * {@link DevicePolicyManager#isAffiliatedUser}
2346 */
2347 public void testUserAffiliation() throws Exception {
2348 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2349 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2350 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2351
2352 // Check that the system user is unaffiliated.
2353 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2354 assertFalse(dpm.isAffiliatedUser());
2355
2356 // Set a device owner on the system user. Check that the system user becomes affiliated.
2357 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2358 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2359 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2360 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002361 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002362
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002363 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002364 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2365 setAsProfileOwner(admin2);
2366 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002367 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002368
2369 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2370 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002371 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002372 userAffiliationIds.add("red");
2373 userAffiliationIds.add("green");
2374 userAffiliationIds.add("blue");
2375 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002376 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002377 assertFalse(dpm.isAffiliatedUser());
2378
2379 // Have the device owner specify a set of affiliation ids that do not intersect with those
2380 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002381 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002382 deviceAffiliationIds.add("cyan");
2383 deviceAffiliationIds.add("yellow");
2384 deviceAffiliationIds.add("magenta");
2385 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2386 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002387 MoreAsserts.assertContentsInAnyOrder(
2388 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002389 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2390 assertFalse(dpm.isAffiliatedUser());
2391
2392 // Have the profile owner specify a set of affiliation ids that intersect with those
2393 // specified by the device owner. Check that the test user becomes affiliated.
2394 userAffiliationIds.add("yellow");
2395 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002396 MoreAsserts.assertContentsInAnyOrder(
2397 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002398 assertTrue(dpm.isAffiliatedUser());
2399
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002400 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002401 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002402 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002403 assertFalse(dpm.isAffiliatedUser());
2404
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002405 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2406 dpm.setAffiliationIds(admin2, userAffiliationIds);
2407 assertTrue(dpm.isAffiliatedUser());
2408 dpm.clearProfileOwner(admin2);
2409 assertFalse(dpm.isAffiliatedUser());
2410
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002411 // Check that the system user remains affiliated.
2412 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2413 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002414
2415 // Clear the device owner - the user becomes unaffiliated.
2416 clearDeviceOwner();
2417 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002418 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002419
2420 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002421 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002422 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2423 }
2424
2425 public void testSetUserProvisioningState_permission() throws Exception {
2426 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002427
2428 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2429 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2430 }
2431
2432 public void testSetUserProvisioningState_unprivileged() throws Exception {
2433 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002434 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2435 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2436 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002437 }
2438
2439 public void testSetUserProvisioningState_noManagement() {
2440 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002441 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002442 assertExpectException(IllegalStateException.class,
2443 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2444 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2445 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002446 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2447 }
2448
2449 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2450 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2451 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002452
2453 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2454 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2455 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2456 }
2457
2458 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2459 throws Exception {
2460 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2461 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002462
2463 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2464 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2465 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2466 }
2467
2468 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2469 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2470 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002471
2472 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2473 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2474 }
2475
2476 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2477 throws Exception {
2478 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002479
2480 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2481 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2482 DevicePolicyManager.STATE_USER_UNMANAGED);
2483 }
2484
2485 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2486 throws Exception {
2487 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002488
2489 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2490 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2491 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2492 }
2493
2494 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2495 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002496
2497 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2498 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2499 }
2500
2501 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2502 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002503
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002504 assertExpectException(IllegalStateException.class,
2505 /* messageRegex= */ "Cannot move to user provisioning state",
2506 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2507 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2508 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002509 }
2510
2511 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2512 throws Exception {
2513 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002514
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002515 assertExpectException(IllegalStateException.class,
2516 /* messageRegex= */ "Cannot move to user provisioning state",
2517 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2518 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2519 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002520 }
2521
2522 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002523 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2524 mContext.callerPermissions.add(permission.MANAGE_USERS);
2525
Alan Treadwayafad8782016-01-19 15:15:08 +00002526 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2527 for (int state : states) {
2528 dpm.setUserProvisioningState(state, userId);
2529 assertEquals(state, dpm.getUserProvisioningState());
2530 }
2531 }
2532
2533 private void setupProfileOwner() throws Exception {
2534 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2535
2536 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2537 dpm.setActiveAdmin(admin1, false);
2538 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2539
2540 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2541 }
2542
2543 private void setupDeviceOwner() throws Exception {
2544 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2545
2546 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2547 dpm.setActiveAdmin(admin1, false);
2548 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2549
2550 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2551 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002552
2553 public void testSetMaximumTimeToLock() {
2554 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2555
2556 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2557 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2558
Pavel Grafov75c0a892017-05-18 17:28:27 +01002559 reset(getServices().powerManagerInternal);
2560 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002561
2562 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002563 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2564 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002565 reset(getServices().powerManagerInternal);
2566 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002567
2568 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002569 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2570 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002571 reset(getServices().powerManagerInternal);
2572 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002573
2574 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002575 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2576 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002577 reset(getServices().powerManagerInternal);
2578 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002579
2580 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002581 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2582 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002583 reset(getServices().powerManagerInternal);
2584 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002585
2586 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002587 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2588 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002589 reset(getServices().powerManagerInternal);
2590 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002591
2592 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002593 reset(getServices().powerManagerInternal);
2594 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002595
Pavel Grafov28939982017-10-03 15:11:52 +01002596 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2597 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2598 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002599 reset(getServices().powerManagerInternal);
2600 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002601
2602 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002603 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2604 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002605 reset(getServices().powerManagerInternal);
2606 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002607
Pavel Grafov28939982017-10-03 15:11:52 +01002608 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002609 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002610 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2611 verifyStayOnWhilePluggedCleared(false);
2612 }
2613
2614 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2615 // uses separate challenge.
2616 public void testSetMaximumTimeToLockProfile() throws Exception {
2617 final int PROFILE_USER = 15;
2618 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2619 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2620 mContext.binder.callingUid = PROFILE_ADMIN;
2621 final DevicePolicyManagerInternal dpmi =
2622 LocalServices.getService(DevicePolicyManagerInternal.class);
2623
2624 dpm.setMaximumTimeToLock(admin1, 0);
2625
2626 reset(getServices().powerManagerInternal);
2627 reset(getServices().settings);
2628
2629 // First add timeout for the profile.
2630 dpm.setMaximumTimeToLock(admin1, 10);
2631 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2632
2633 reset(getServices().powerManagerInternal);
2634 reset(getServices().settings);
2635
2636 // Add separate challenge
2637 when(getServices().lockPatternUtils
2638 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2639 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2640
2641 verifyScreenTimeoutCall(10L, PROFILE_USER);
2642 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2643
2644 reset(getServices().powerManagerInternal);
2645 reset(getServices().settings);
2646
2647 // Remove the timeout.
2648 dpm.setMaximumTimeToLock(admin1, 0);
2649 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2650 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2651
2652 reset(getServices().powerManagerInternal);
2653 reset(getServices().settings);
2654
2655 // Add it back.
2656 dpm.setMaximumTimeToLock(admin1, 10);
2657 verifyScreenTimeoutCall(10L, PROFILE_USER);
2658 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2659
2660 reset(getServices().powerManagerInternal);
2661 reset(getServices().settings);
2662
2663 // Remove separate challenge.
2664 reset(getServices().lockPatternUtils);
2665 when(getServices().lockPatternUtils
2666 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2667 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002668 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002669
2670 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2671 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2672
2673 reset(getServices().powerManagerInternal);
2674 reset(getServices().settings);
2675
2676 // Remove the timeout.
2677 dpm.setMaximumTimeToLock(admin1, 0);
2678 verifyScreenTimeoutCall(null, PROFILE_USER);
2679 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002680 }
2681
Michal Karpinski943aabd2016-10-06 11:09:25 +01002682 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2683 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2684 setupDeviceOwner();
2685 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2686
Michal Karpinskid084ca52017-01-18 15:54:18 +00002687 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2688 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2689 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2690 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2691 - ONE_MINUTE;
2692
2693 // verify that the minimum timeout cannot be modified on user builds (system property is
2694 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002695 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002696
2697 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2698 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2699 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2700
Pavel Grafov75c0a892017-05-18 17:28:27 +01002701 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002702
2703 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002704 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002705
Michal Karpinskid084ca52017-01-18 15:54:18 +00002706 // reset to default (0 means the admin is not participating, so default should be returned)
2707 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002708
2709 // aggregation should be the default if unset by any admin
2710 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2711 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2712
2713 // admin not participating by default
2714 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2715
2716 //clamping from the top
2717 dpm.setRequiredStrongAuthTimeout(admin1,
2718 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2719 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2720 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2721 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2722 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2723
Michal Karpinskid084ca52017-01-18 15:54:18 +00002724 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002725 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2726 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2727 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2728 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2729
2730 // clamping from the bottom
2731 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2732 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2733 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2734
Michal Karpinskid084ca52017-01-18 15:54:18 +00002735 // values within range
2736 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2737 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2738 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2739
2740 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2741 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2742 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002743
2744 // reset to default
2745 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2746 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2747 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2748 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2749
2750 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002751 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2752 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002753 }
2754
Pavel Grafov28939982017-10-03 15:11:52 +01002755 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002756 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002757 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002758 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002759 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002760 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002761 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002762 }
Pavel Grafov28939982017-10-03 15:11:52 +01002763 }
2764
2765 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002766 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2767 // UnfinishedVerificationException.
2768 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002769
Esteban Talavera01576862016-12-15 11:16:44 +00002770 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002771 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002772 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002773 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002774 .thenReturn(false);
2775 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002776 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2777 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002778 .thenReturn(true);
2779 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2780
2781 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002782 }
Victor Chang3e794af2016-03-04 13:48:17 +00002783
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002784 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2785 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002786 mContext.packageName = admin1.getPackageName();
2787 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002788 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2790 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2791 false);
2792 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2793 }
2794
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002795 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2796 setup_DeviceAdminFeatureOff();
2797 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2798 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2799 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2800 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2801 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2802 assertCheckProvisioningPreCondition(
2803 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2804 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2805 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2806 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2807 }
2808
Esteban Talavera01576862016-12-15 11:16:44 +00002809 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002810 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002811 .thenReturn(false);
2812 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002813 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2814 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002815 .thenReturn(true);
2816 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2817
2818 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002819 }
Victor Chang3e794af2016-03-04 13:48:17 +00002820
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002821 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2822 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002823 mContext.packageName = admin1.getPackageName();
2824 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002825 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2826 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2827 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2828 false);
2829 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2830
2831 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002832 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002833 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2834 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2835 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2836 true);
2837 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2838 }
2839
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002840 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2841 setup_ManagedProfileFeatureOff();
2842 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2843 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2844 DevicePolicyManager.CODE_OK);
2845 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2846 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2847 assertCheckProvisioningPreCondition(
2848 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2849 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2850 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2851 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2852
2853 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002854 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002855 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2856 DevicePolicyManager.CODE_OK);
2857 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2858 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2859 assertCheckProvisioningPreCondition(
2860 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2861 DevicePolicyManager.CODE_OK);
2862 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2863 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2864 }
2865
Esteban Talavera01576862016-12-15 11:16:44 +00002866 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002867 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002868 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002869 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2870 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002871 .thenReturn(true);
2872 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2873
2874 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002875 }
Victor Chang3e794af2016-03-04 13:48:17 +00002876
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002877 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2878 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002879 mContext.packageName = admin1.getPackageName();
2880 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002881 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2883 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2884 false /* because of non-split user */);
2885 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2886 false /* because of non-split user */);
2887 }
2888
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002889 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002890 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002891 setup_nonSplitUser_firstBoot_primaryUser();
2892 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2893 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2894 DevicePolicyManager.CODE_OK);
2895 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2896 DevicePolicyManager.CODE_OK);
2897 assertCheckProvisioningPreCondition(
2898 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2899 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2900 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2901 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2902 }
2903
Esteban Talavera01576862016-12-15 11:16:44 +00002904 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002905 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002906 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002907 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2908 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002909 .thenReturn(true);
2910 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2911
2912 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002913 }
Victor Chang3e794af2016-03-04 13:48:17 +00002914
Nicolas Prevot45d29072017-01-18 16:11:19 +00002915 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2916 setDeviceOwner();
2917 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2918 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2919 }
2920
2921 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2922 setup_nonSplitUser_withDo_primaryUser();
2923 final int MANAGED_PROFILE_USER_ID = 18;
2924 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2925 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002926 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002927 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002928 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002929 true)).thenReturn(true);
2930 }
2931
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002932 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2933 throws Exception {
2934 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002935 mContext.packageName = admin1.getPackageName();
2936 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002937 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2938 false/* because of completed device setup */);
2939 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2940 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2941 false/* because of non-split user */);
2942 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2943 false/* because of non-split user */);
2944 }
2945
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002946 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2947 throws Exception {
2948 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2949 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2950 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2951 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2952 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2953 DevicePolicyManager.CODE_OK);
2954 assertCheckProvisioningPreCondition(
2955 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2956 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2957 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2958 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2959 }
2960
Nicolas Prevot45d29072017-01-18 16:11:19 +00002961 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2962 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002963 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002964 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2965
2966 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2967 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002968 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002969
2970 // COMP mode is allowed.
2971 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2972 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002973 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002974
Nicolas Prevot45d29072017-01-18 16:11:19 +00002975 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002976 assertCheckProvisioningPreCondition(
2977 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002978 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002979 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002980 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2981 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2982 }
Esteban Talavera01576862016-12-15 11:16:44 +00002983
Nicolas Prevot45d29072017-01-18 16:11:19 +00002984 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2985 setup_nonSplitUser_withDo_primaryUser();
2986 mContext.packageName = admin1.getPackageName();
2987 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2988 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2989 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002990 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00002991 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2992 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2993 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002994 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00002995 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2996 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2997 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2998 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2999 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003001 assertCheckProvisioningPreCondition(
3002 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003003 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003004 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003005 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3006 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3007 }
Esteban Talavera01576862016-12-15 11:16:44 +00003008
Nicolas Prevot45d29072017-01-18 16:11:19 +00003009 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3010 throws Exception {
3011 setup_nonSplitUser_withDo_primaryUser();
3012 mContext.packageName = admin1.getPackageName();
3013 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003014 // The DO should not be allowed to initiate provisioning if the restriction is set by
3015 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003016 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003017 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3018 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3019 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003020 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003021 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3022 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3023 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3024 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3025 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3027
3028 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003029 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003030 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003031 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003032 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3033 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3034 }
3035
3036 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3037 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3038 mContext.packageName = admin1.getPackageName();
3039 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3040
3041 // We can delete the managed profile to create a new one, so provisioning is allowed.
3042 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3043 DevicePolicyManager.CODE_OK);
3044 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3045 assertCheckProvisioningPreCondition(
3046 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3047 DpmMockContext.ANOTHER_PACKAGE_NAME,
3048 DevicePolicyManager.CODE_OK);
3049 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3050 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3051 }
3052
3053 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3054 throws Exception {
3055 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3056 mContext.packageName = admin1.getPackageName();
3057 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003058 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003059 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3060 eq(UserHandle.SYSTEM)))
3061 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003062 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003063 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3064 eq(UserHandle.SYSTEM)))
3065 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003066
3067 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003068 assertCheckProvisioningPreCondition(
3069 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3070 DpmMockContext.ANOTHER_PACKAGE_NAME,
3071 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3072 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3073 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003074
3075 // But the device owner can still do it because it has set the restriction itself.
3076 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3077 DevicePolicyManager.CODE_OK);
3078 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003079 }
3080
3081 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003082 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003083 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003084 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3085 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003086 .thenReturn(false);
3087 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3088
3089 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003090 }
Victor Chang3e794af2016-03-04 13:48:17 +00003091
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003092 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3093 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003094 mContext.packageName = admin1.getPackageName();
3095 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003096 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3097 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3098 false /* because canAddMoreManagedProfiles returns false */);
3099 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3100 true);
3101 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3102 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003103 }
3104
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003105 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3106 throws Exception {
3107 setup_splitUser_firstBoot_systemUser();
3108 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3109 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3110 DevicePolicyManager.CODE_OK);
3111 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003112 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003113 assertCheckProvisioningPreCondition(
3114 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3115 DevicePolicyManager.CODE_OK);
3116 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3117 DevicePolicyManager.CODE_SYSTEM_USER);
3118 }
3119
Esteban Talavera01576862016-12-15 11:16:44 +00003120 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003121 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003122 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003123 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3124 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003125 .thenReturn(false);
3126 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3127
3128 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003129 }
Victor Chang3e794af2016-03-04 13:48:17 +00003130
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003131 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3132 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003133 mContext.packageName = admin1.getPackageName();
3134 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003135 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3136 true/* it's undefined behavior. Can be changed into false in the future */);
3137 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3138 false /* because canAddMoreManagedProfiles returns false */);
3139 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3140 true/* it's undefined behavior. Can be changed into false in the future */);
3141 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3142 false/* because calling uid is system user */);
3143 }
3144
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003145 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3146 throws Exception {
3147 setup_splitUser_afterDeviceSetup_systemUser();
3148 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3149 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3150 DevicePolicyManager.CODE_OK);
3151 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003152 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003153 assertCheckProvisioningPreCondition(
3154 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3155 DevicePolicyManager.CODE_OK);
3156 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3157 DevicePolicyManager.CODE_SYSTEM_USER);
3158 }
3159
Esteban Talavera01576862016-12-15 11:16:44 +00003160 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003161 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003162 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003163 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3164 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003165 true)).thenReturn(true);
3166 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3167
3168 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003169 }
Victor Chang3e794af2016-03-04 13:48:17 +00003170
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003171 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3172 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003173 mContext.packageName = admin1.getPackageName();
3174 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003175 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3176 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3177 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3178 true);
3179 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003180 }
3181
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003182 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003183 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003184 setup_splitUser_firstBoot_primaryUser();
3185 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3186 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3187 DevicePolicyManager.CODE_OK);
3188 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3189 DevicePolicyManager.CODE_OK);
3190 assertCheckProvisioningPreCondition(
3191 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3192 DevicePolicyManager.CODE_OK);
3193 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3194 DevicePolicyManager.CODE_OK);
3195 }
3196
Esteban Talavera01576862016-12-15 11:16:44 +00003197 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003198 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003199 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003200 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3201 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003202 true)).thenReturn(true);
3203 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3204
3205 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003206 }
Victor Chang3e794af2016-03-04 13:48:17 +00003207
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003208 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3209 throws Exception {
3210 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003211 mContext.packageName = admin1.getPackageName();
3212 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003213 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3214 true/* it's undefined behavior. Can be changed into false in the future */);
3215 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3216 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3217 true/* it's undefined behavior. Can be changed into false in the future */);
3218 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3219 false/* because user setup completed */);
3220 }
3221
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003222 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003223 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003224 setup_splitUser_afterDeviceSetup_primaryUser();
3225 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3226 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3227 DevicePolicyManager.CODE_OK);
3228 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3229 DevicePolicyManager.CODE_OK);
3230 assertCheckProvisioningPreCondition(
3231 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3232 DevicePolicyManager.CODE_OK);
3233 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3234 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3235 }
3236
Esteban Talavera01576862016-12-15 11:16:44 +00003237 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003238 setDeviceOwner();
3239
Pavel Grafov75c0a892017-05-18 17:28:27 +01003240 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003241 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003242 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3243 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003244 .thenReturn(false);
3245 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3246
3247 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003248 }
Victor Chang3e794af2016-03-04 13:48:17 +00003249
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003250 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3251 throws Exception {
3252 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003253 mContext.packageName = admin1.getPackageName();
3254 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003255 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3256 false /* can't provision managed profile on system user */);
3257 }
3258
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003259 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003260 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003261 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3262 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3263 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3264 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3265 }
3266
3267 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003268 setDeviceOwner();
3269
Pavel Grafov75c0a892017-05-18 17:28:27 +01003270 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003271 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003272 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3273 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003274 true)).thenReturn(true);
3275 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3276
3277 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003278 }
Victor Chang3e794af2016-03-04 13:48:17 +00003279
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003280 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3281 throws Exception {
3282 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003283 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3284 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003285 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3286 }
3287
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003288 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003289 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003290 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3291 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003292
3293 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003294 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3295 DevicePolicyManager.CODE_OK);
3296 }
3297
3298 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003299 setDeviceOwner();
3300
Pavel Grafov75c0a892017-05-18 17:28:27 +01003301 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003302 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003303 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3304 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003305 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3306 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003307 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003308 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003309 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003310 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003311 true)).thenReturn(true);
3312 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3313
3314 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003315 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003316
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003317 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3318 throws Exception {
3319 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003320 mContext.packageName = admin1.getPackageName();
3321 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003322 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3323 }
3324
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003325 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3326 throws Exception {
3327 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3328 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3329 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3330 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3331 }
3332
3333 public void testCheckProvisioningPreCondition_permission() {
3334 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003335 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3336 () -> dpm.checkProvisioningPreCondition(
3337 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003338 }
3339
Victor Chang3577ed22016-08-25 18:49:26 +01003340 public void testForceUpdateUserSetupComplete_permission() {
3341 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003342 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3343 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003344 }
3345
3346 public void testForceUpdateUserSetupComplete_systemUser() {
3347 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3348 // GIVEN calling from user 20
3349 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003350 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3351 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003352 }
3353
3354 public void testForceUpdateUserSetupComplete_userbuild() {
3355 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3356 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3357
3358 final int userId = UserHandle.USER_SYSTEM;
3359 // GIVEN userComplete is false in SettingsProvider
3360 setUserSetupCompleteForUser(false, userId);
3361
3362 // GIVEN userComplete is true in DPM
3363 DevicePolicyManagerService.DevicePolicyData userData =
3364 new DevicePolicyManagerService.DevicePolicyData(userId);
3365 userData.mUserSetupComplete = true;
3366 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3367
3368 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003369 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003370
3371 assertTrue(dpms.hasUserSetupCompleted());
3372
3373 dpm.forceUpdateUserSetupComplete();
3374
3375 // THEN the state in dpms is not changed
3376 assertTrue(dpms.hasUserSetupCompleted());
3377 }
3378
3379 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3380 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3381 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3382
3383 final int userId = UserHandle.USER_SYSTEM;
3384 // GIVEN userComplete is false in SettingsProvider
3385 setUserSetupCompleteForUser(false, userId);
3386
3387 // GIVEN userComplete is true in DPM
3388 DevicePolicyManagerService.DevicePolicyData userData =
3389 new DevicePolicyManagerService.DevicePolicyData(userId);
3390 userData.mUserSetupComplete = true;
3391 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3392
3393 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003394 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003395
3396 assertTrue(dpms.hasUserSetupCompleted());
3397
3398 dpm.forceUpdateUserSetupComplete();
3399
3400 // THEN the state in dpms is not changed
3401 assertFalse(dpms.hasUserSetupCompleted());
3402 }
3403
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003404 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003405 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003406 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003407
3408 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3409 runAsCaller(mAdmin1Context, dpms, dpm -> {
3410 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3411 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003412 }
3413
3414 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3415 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3416 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003417
3418 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3419 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003420 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003421 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3422 .thenReturn(true);
3423
3424 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003425 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003426
3427 // Enabling logging should not change the timestamp.
3428 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003429 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003430 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003431 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003432 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003433 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003434
3435 // Retrieving the logs should update the timestamp.
3436 final long beforeRetrieval = System.currentTimeMillis();
3437 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003438 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003439 final long afterRetrieval = System.currentTimeMillis();
3440 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3441 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3442
3443 // Retrieving the pre-boot logs should update the timestamp.
3444 Thread.sleep(2);
3445 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003446 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003447 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3448
3449 // Checking the timestamp again should not change it.
3450 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003451 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003452
3453 // Retrieving the logs again should update the timestamp.
3454 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003455 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003456 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3457
3458 // Disabling logging should not change the timestamp.
3459 Thread.sleep(2);
3460 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003461 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003462
3463 // Restarting the DPMS should not lose the timestamp.
3464 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003465 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003466
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003467 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3468 mContext.binder.callingUid = 1234567;
3469 mContext.callerPermissions.add(permission.MANAGE_USERS);
3470 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3471 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3472
3473 // System can retrieve the timestamp.
3474 mContext.binder.clearCallingIdentity();
3475 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3476
3477 // Removing the device owner should clear the timestamp.
3478 clearDeviceOwner();
3479 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003480 }
3481
yuemingw0de748d2017-11-15 19:22:27 +00003482 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3483 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3484 setupDeviceOwner();
3485 assertExpectException(SecurityException.class, null, () ->
3486 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3487 }
3488
yuemingwc0281f12018-03-28 15:58:49 +01003489 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003490 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3491 setupDeviceOwner();
3492 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003493 verify(getServices().settings).settingsSystemPutStringForUser(
3494 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3495 }
3496
3497 public void testSetSystemSettingWithPO() throws Exception {
3498 setupProfileOwner();
3499 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3500 verify(getServices().settings).settingsSystemPutStringForUser(
3501 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003502 }
3503
yuemingwe43cdf72017-10-12 16:52:11 +01003504 public void testSetTime() throws Exception {
3505 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3506 setupDeviceOwner();
3507 dpm.setTime(admin1, 0);
3508 verify(getServices().alarmManager).setTime(0);
3509 }
3510
3511 public void testSetTimeFailWithPO() throws Exception {
3512 setupProfileOwner();
3513 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3514 }
3515
3516 public void testSetTimeWithAutoTimeOn() throws Exception {
3517 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3518 setupDeviceOwner();
3519 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3520 .thenReturn(1);
3521 assertFalse(dpm.setTime(admin1, 0));
3522 }
3523
3524 public void testSetTimeZone() throws Exception {
3525 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3526 setupDeviceOwner();
3527 dpm.setTimeZone(admin1, "Asia/Shanghai");
3528 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3529 }
3530
3531 public void testSetTimeZoneFailWithPO() throws Exception {
3532 setupProfileOwner();
3533 assertExpectException(SecurityException.class, null,
3534 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3535 }
3536
3537 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3539 setupDeviceOwner();
3540 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3541 .thenReturn(1);
3542 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3543 }
3544
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003545 public void testGetLastBugReportRequestTime() throws Exception {
3546 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3547 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003548
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003549 mContext.packageName = admin1.getPackageName();
3550 mContext.applicationInfo = new ApplicationInfo();
3551 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3552 .thenReturn(Color.WHITE);
3553 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3554 anyObject())).thenReturn(Color.WHITE);
3555
Esteban Talaverad36dd152016-12-15 08:51:45 +00003556 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3557 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003558 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003559
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003560 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003561 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003562
3563 // Requesting a bug report should update the timestamp.
3564 final long beforeRequest = System.currentTimeMillis();
3565 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003566 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003567 final long afterRequest = System.currentTimeMillis();
3568 assertTrue(bugReportRequestTime >= beforeRequest);
3569 assertTrue(bugReportRequestTime <= afterRequest);
3570
3571 // Checking the timestamp again should not change it.
3572 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003573 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003574
3575 // Restarting the DPMS should not lose the timestamp.
3576 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003577 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003578
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003579 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3580 mContext.binder.callingUid = 1234567;
3581 mContext.callerPermissions.add(permission.MANAGE_USERS);
3582 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3583 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3584
3585 // System can retrieve the timestamp.
3586 mContext.binder.clearCallingIdentity();
3587 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3588
3589 // Removing the device owner should clear the timestamp.
3590 clearDeviceOwner();
3591 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003592 }
3593
3594 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3595 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3596 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003597 mContext.packageName = admin1.getPackageName();
3598 mContext.applicationInfo = new ApplicationInfo();
3599 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3600 .thenReturn(Color.WHITE);
3601 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3602 anyObject())).thenReturn(Color.WHITE);
3603
3604 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3605 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003606 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003607 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003608 .thenReturn(true);
3609
3610 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003611 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003612
3613 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3614 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003615 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003616
3617 // Enabling logging should not change the timestamp.
3618 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003619 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003620
3621 // Retrieving the logs should update the timestamp.
3622 final long beforeRetrieval = System.currentTimeMillis();
3623 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003624 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003625 final long afterRetrieval = System.currentTimeMillis();
3626 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3627 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3628
3629 // Checking the timestamp again should not change it.
3630 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003631 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003632
3633 // Retrieving the logs again should update the timestamp.
3634 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003635 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003636 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3637
3638 // Disabling logging should not change the timestamp.
3639 Thread.sleep(2);
3640 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003641 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003642
3643 // Restarting the DPMS should not lose the timestamp.
3644 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003645 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3646
3647 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3648 mContext.binder.callingUid = 1234567;
3649 mContext.callerPermissions.add(permission.MANAGE_USERS);
3650 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3651 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3652
3653 // System can retrieve the timestamp.
3654 mContext.binder.clearCallingIdentity();
3655 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3656
3657 // Removing the device owner should clear the timestamp.
3658 clearDeviceOwner();
3659 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003660 }
3661
Tony Mak2f26b792016-11-28 17:54:51 +00003662 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3663 // Setup device owner.
3664 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3665 setupDeviceOwner();
3666
3667 // Only device owner is setup, the result list should be empty.
3668 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3669 MoreAsserts.assertEmpty(targetUsers);
3670
3671 // Setup a managed profile managed by the same admin.
3672 final int MANAGED_PROFILE_USER_ID = 15;
3673 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3674 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3675
3676 // Add a secondary user, it should never talk with.
3677 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003678 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003679
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003680 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3681 // other.
3682 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3683 MoreAsserts.assertEmpty(targetUsers);
3684
3685 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3686 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3687 MoreAsserts.assertEmpty(targetUsers);
3688
3689 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003690 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003691 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3692 dpm.setAffiliationIds(admin1, userAffiliationIds);
3693
3694 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3695 dpm.setAffiliationIds(admin1, userAffiliationIds);
3696
Tony Mak2f26b792016-11-28 17:54:51 +00003697 // Calling from device owner admin, the result list should just contain the managed
3698 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003699 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003700 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3701 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3702
3703 // Calling from managed profile admin, the result list should just contain the system
3704 // user id.
3705 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3706 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3707 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003708
3709 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003710 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003711
3712 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3713 // to each other.
3714 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3715 MoreAsserts.assertEmpty(targetUsers);
3716
3717 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3718 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3719 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003720 }
3721
3722 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3723 // Setup a device owner.
3724 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3725 setupDeviceOwner();
3726
3727 // Set up a managed profile managed by different package.
3728 final int MANAGED_PROFILE_USER_ID = 15;
3729 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3730 final ComponentName adminDifferentPackage =
3731 new ComponentName("another.package", "whatever.class");
3732 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3733
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003734 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003735 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003736 dpm.setAffiliationIds(admin1, userAffiliationIds);
3737
3738 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3739 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3740
Tony Mak2f26b792016-11-28 17:54:51 +00003741 // Calling from device owner admin, we should get zero bind device admin target users as
3742 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003743 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003744 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3745 MoreAsserts.assertEmpty(targetUsers);
3746
3747 // Calling from managed profile admin, we should still get zero target users for the same
3748 // reason.
3749 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3750 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3751 MoreAsserts.assertEmpty(targetUsers);
3752 }
3753
Jason Parks3c13b642017-11-28 15:39:43 -06003754 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003755 verifyLockTaskState(userId, new String[0],
3756 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003757 }
3758
3759 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3760 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003761 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003762 }
3763
3764 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3765 int flags) throws Exception {
3766 mContext.binder.callingUid = uid;
3767 dpm.setLockTaskPackages(who, packages);
3768 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3769 for (String p : packages) {
3770 assertTrue(dpm.isLockTaskPermitted(p));
3771 }
3772 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3773 // Test to see if set lock task features can be set
3774 dpm.setLockTaskFeatures(who, flags);
3775 verifyLockTaskState(userId, packages, flags);
3776 }
3777
3778 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3779 int flags) throws Exception {
3780 mContext.binder.callingUid = uid;
3781 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3782 () -> dpm.setLockTaskPackages(who, packages));
3783 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3784 () -> dpm.getLockTaskPackages(who));
3785 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3786 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3787 () -> dpm.setLockTaskFeatures(who, flags));
3788 }
3789
Charles Hee078db72017-10-19 18:03:20 +01003790 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003791 // Setup a device owner.
3792 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3793 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003794 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003795 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003796
3797 // Set up a managed profile managed by different package (package name shouldn't matter)
3798 final int MANAGED_PROFILE_USER_ID = 15;
3799 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3800 final ComponentName adminDifferentPackage =
3801 new ComponentName("another.package", "whatever.class");
3802 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003803 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3804
3805 // Setup a PO on the secondary user
3806 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3807 setAsProfileOwner(admin3);
3808 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003809
3810 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003811 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003812 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003813 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3814 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003815 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3816
3817 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3818 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003819 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3820 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003821 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003822
3823 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3824 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3825 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003826 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003827 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3828 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003829 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003830
3831 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003832 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003833 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3834 dpm.setAffiliationIds(admin1, userAffiliationIds);
3835
3836 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3837 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3838
3839 // Now the managed profile can set lock task packages.
3840 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3841 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3842 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3843 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003844 // And it can set lock task features.
3845 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003846 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003847
3848 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003849 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003850 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3851 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003852 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3853 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003854 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003855 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003856
Jason Parks3c13b642017-11-28 15:39:43 -06003857 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3859 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003860
3861 }
3862
3863 public void testLockTaskPolicyForProfileOwner() throws Exception {
3864 // Setup a PO
3865 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3866 setAsProfileOwner(admin1);
3867 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3868
3869 final String[] poPackages = {"poPackage1", "poPackage2"};
3870 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003871 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3872 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003873 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3874 poPackages, poFlags);
3875
3876 // Set up a managed profile managed by different package (package name shouldn't matter)
3877 final int MANAGED_PROFILE_USER_ID = 15;
3878 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3879 final ComponentName adminDifferentPackage =
3880 new ComponentName("another.package", "whatever.class");
3881 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3882 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3883
3884 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3885 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3886 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3887 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003888 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3889 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003890 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003891 }
3892
Benjamin Franzcaffa772018-02-05 16:36:10 +00003893 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3894 // Setup a device owner.
3895 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3896 setupDeviceOwner();
3897 // Lock task policy is updated when loading user data.
3898 verifyLockTaskState(UserHandle.USER_SYSTEM);
3899
3900 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3901 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3902 assertExpectException(IllegalArgumentException.class,
3903 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
3904 () -> dpm.setLockTaskFeatures(admin1, flags));
3905 }
3906
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003907 public void testIsDeviceManaged() throws Exception {
3908 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3909 setupDeviceOwner();
3910
3911 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3912 // find out that the device has a device owner.
3913 assertTrue(dpm.isDeviceManaged());
3914 mContext.binder.callingUid = 1234567;
3915 mContext.callerPermissions.add(permission.MANAGE_USERS);
3916 assertTrue(dpm.isDeviceManaged());
3917 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3918 mContext.binder.clearCallingIdentity();
3919 assertTrue(dpm.isDeviceManaged());
3920
3921 clearDeviceOwner();
3922
3923 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3924 // not have a device owner.
3925 mContext.binder.callingUid = 1234567;
3926 mContext.callerPermissions.add(permission.MANAGE_USERS);
3927 assertFalse(dpm.isDeviceManaged());
3928 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3929 mContext.binder.clearCallingIdentity();
3930 assertFalse(dpm.isDeviceManaged());
3931 }
3932
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003933 public void testDeviceOwnerOrganizationName() throws Exception {
3934 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3935 setupDeviceOwner();
3936
3937 dpm.setOrganizationName(admin1, "organization");
3938
3939 // Device owner can retrieve organization managing the device.
3940 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3941
3942 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3943 mContext.binder.callingUid = 1234567;
3944 mContext.callerPermissions.add(permission.MANAGE_USERS);
3945 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3946 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3947
3948 // System can retrieve organization managing the device.
3949 mContext.binder.clearCallingIdentity();
3950 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3951
3952 // Removing the device owner clears the organization managing the device.
3953 clearDeviceOwner();
3954 assertNull(dpm.getDeviceOwnerOrganizationName());
3955 }
3956
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003957 public void testWipeDataManagedProfile() throws Exception {
3958 final int MANAGED_PROFILE_USER_ID = 15;
3959 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3960 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3961 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3962
3963 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003964 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003965 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01003966 // Get mock reason string since we throw an IAE with empty string input.
3967 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3968 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003969
3970 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003971 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003972 MANAGED_PROFILE_USER_ID);
3973 }
3974
3975 public void testWipeDataManagedProfileDisallowed() throws Exception {
3976 final int MANAGED_PROFILE_USER_ID = 15;
3977 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3978 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3979
3980 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01003981 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003982 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3983
Pavel Grafov75c0a892017-05-18 17:28:27 +01003984 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003985 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3986 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3987 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01003988 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
3989 thenReturn("Just a test string.");
3990
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003991 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003992 // The PO is not allowed to remove the profile if the user restriction was set on the
3993 // profile by the system
3994 assertExpectException(SecurityException.class, /* messageRegex= */ null,
3995 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003996 }
3997
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003998 public void testWipeDataDeviceOwner() throws Exception {
3999 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004000 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004001 UserManager.DISALLOW_FACTORY_RESET,
4002 UserHandle.SYSTEM))
4003 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004004 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4005 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004006
4007 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004008 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004009 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4010 /*wipeEuicc=*/ eq(false));
4011 }
4012
4013 public void testWipeEuiccDataEnabled() throws Exception {
4014 setDeviceOwner();
4015 when(getServices().userManager.getUserRestrictionSource(
4016 UserManager.DISALLOW_FACTORY_RESET,
4017 UserHandle.SYSTEM))
4018 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004019 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4020 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004021
4022 dpm.wipeData(WIPE_EUICC);
4023 verify(getServices().recoverySystem).rebootWipeUserData(
4024 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4025 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004026 }
4027
4028 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4029 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004030 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004031 UserManager.DISALLOW_FACTORY_RESET,
4032 UserHandle.SYSTEM))
4033 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004034 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4035 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004036 // The DO is not allowed to wipe the device if the user restriction was set
4037 // by the system
4038 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4039 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004040 }
4041
4042 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4043 final int MANAGED_PROFILE_USER_ID = 15;
4044 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4045 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4046
4047 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004048 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004049 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4050
Pavel Grafov75c0a892017-05-18 17:28:27 +01004051 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004052 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4053 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4054 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4055
4056 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4057 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4058
4059 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4060 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4061 // Failed password attempts on the parent user are taken into account, as there isn't a
4062 // separate work challenge.
4063 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4064 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4065 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4066
4067 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4068 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004069 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004070 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004071 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004072 }
4073
4074 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4075 throws Exception {
4076 final int MANAGED_PROFILE_USER_ID = 15;
4077 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4078 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4079
4080 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004081 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004082 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4083
Pavel Grafov75c0a892017-05-18 17:28:27 +01004084 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004085 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4086 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4087 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4088
4089 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4090 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4091
4092 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4093 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4094 // Failed password attempts on the parent user are taken into account, as there isn't a
4095 // separate work challenge.
4096 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4097 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4098 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4099
4100 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4101 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004102 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004103 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004104 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004105 }
4106
4107 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4108 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004109 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004110 UserManager.DISALLOW_FACTORY_RESET,
4111 UserHandle.SYSTEM))
4112 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4113
4114 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4115
4116 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4117 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4118 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4119 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4120 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4121
4122 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4123 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004124 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004125 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4126 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004127 }
4128
4129 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4130 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004131 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004132 UserManager.DISALLOW_FACTORY_RESET,
4133 UserHandle.SYSTEM))
4134 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4135
4136 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4137
4138 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4139 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4140 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4141 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4142 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4143
4144 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004145 verifyZeroInteractions(getServices().recoverySystem);
4146 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004147 .removeUserEvenWhenDisallowed(anyInt());
4148 }
4149
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004150 public void testGetPermissionGrantState() throws Exception {
4151 final String permission = "some.permission";
4152 final String app1 = "com.example.app1";
4153 final String app2 = "com.example.app2";
4154
Pavel Grafov75c0a892017-05-18 17:28:27 +01004155 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004156 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004157 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004158 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004159 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004160 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4161 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004162 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004163 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004164 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004165 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004166 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004167 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4168
4169 // System can retrieve permission grant state.
4170 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004171 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004172 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4173 dpm.getPermissionGrantState(null, app1, permission));
4174 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4175 dpm.getPermissionGrantState(null, app2, permission));
4176
4177 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004178 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4179 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004180 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4181 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004182
4183 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004184 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4185 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004186 setAsProfileOwner(admin1);
4187 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4188 dpm.getPermissionGrantState(admin1, app1, permission));
4189 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4190 dpm.getPermissionGrantState(admin1, app2, permission));
4191 }
4192
Rubin Xuaab7a412016-12-30 21:13:29 +00004193 public void testResetPasswordWithToken() throws Exception {
4194 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4195 setupDeviceOwner();
4196 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004197 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4198 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4199
Rubin Xuaab7a412016-12-30 21:13:29 +00004200 // test adding a token
4201 final byte[] token = new byte[32];
4202 final long handle = 123456;
4203 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004204 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4205 nullable(EscrowTokenStateChangeCallback.class)))
4206 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004207 assertTrue(dpm.setResetPasswordToken(admin1, token));
4208
4209 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004210 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004211 .thenReturn(true);
4212 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4213
4214 // test reset password with token
Rich Canningsf64ec632019-02-21 12:40:36 -08004215 when(getServices().lockPatternUtils.setLockCredentialWithToken(eq(password.getBytes()),
Rubin Xu7cf45092017-08-28 11:47:35 +01004216 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD),
Adrian Roosebf84c22018-12-06 17:50:41 +01004217 eq(DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC), eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004218 eq(UserHandle.USER_SYSTEM)))
4219 .thenReturn(true);
4220 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4221
4222 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004223 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004224 .thenReturn(true);
4225 assertTrue(dpm.clearResetPasswordToken(admin1));
4226 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004227
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004228 public void testIsActivePasswordSufficient() throws Exception {
4229 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4230 mContext.packageName = admin1.getPackageName();
4231 setupDeviceOwner();
4232
4233 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4234 dpm.setPasswordMinimumLength(admin1, 8);
4235 dpm.setPasswordMinimumLetters(admin1, 6);
4236 dpm.setPasswordMinimumLowerCase(admin1, 3);
4237 dpm.setPasswordMinimumUpperCase(admin1, 1);
4238 dpm.setPasswordMinimumNonLetter(admin1, 1);
4239 dpm.setPasswordMinimumNumeric(admin1, 1);
4240 dpm.setPasswordMinimumSymbols(admin1, 0);
4241
Rubin Xucc391c22018-01-02 20:37:35 +00004242 reset(mContext.spiedContext);
4243
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004244 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
4245 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4246 8, 2,
4247 6, 1,
4248 0, 1);
4249
4250 setActivePasswordState(passwordMetricsNoSymbols);
4251 assertTrue(dpm.isActivePasswordSufficient());
4252
4253 initializeDpms();
4254 reset(mContext.spiedContext);
4255 assertTrue(dpm.isActivePasswordSufficient());
4256
4257 // This call simulates the user entering the password for the first time after a reboot.
4258 // This causes password metrics to be reloaded into memory. Until this happens,
4259 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4260 // even if the DPC changes password requirements so that the password no longer meets the
4261 // requirements. This is a known limitation of the current implementation of
4262 // isActivePasswordSufficient() - see b/34218769.
4263 setActivePasswordState(passwordMetricsNoSymbols);
4264 assertTrue(dpm.isActivePasswordSufficient());
4265
4266 dpm.setPasswordMinimumSymbols(admin1, 1);
4267 // This assertion would fail if we had not called setActivePasswordState() again after
4268 // initializeDpms() - see previous comment.
4269 assertFalse(dpm.isActivePasswordSufficient());
4270
4271 initializeDpms();
4272 reset(mContext.spiedContext);
4273 assertFalse(dpm.isActivePasswordSufficient());
4274
4275 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
4276 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
4277 7, 2,
4278 5, 1,
4279 1, 2);
4280
4281 setActivePasswordState(passwordMetricsWithSymbols);
4282 assertTrue(dpm.isActivePasswordSufficient());
4283 }
4284
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004285 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4286 // If there is no lock screen, the password is considered empty no matter what, because
4287 // it provides no security.
4288 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4289
4290 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4291 mContext.packageName = admin1.getPackageName();
4292 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004293 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4294 // When there is no lockscreen, user password metrics is always empty.
4295 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4296 .thenReturn(new PasswordMetrics());
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004297
4298 // If no password requirements are set, isActivePasswordSufficient should succeed.
4299 assertTrue(dpm.isActivePasswordSufficient());
4300
4301 // Now set some password quality requirements.
4302 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4303
4304 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004305 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004306 dpm.reportPasswordChanged(userHandle);
4307
4308 // No broadcast should be sent.
4309 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4310 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4311 MockUtils.checkUserHandle(userHandle));
4312
4313 // The active (nonexistent) password doesn't comply with the requirements.
4314 assertFalse(dpm.isActivePasswordSufficient());
4315 }
4316
Pavel Grafov75c0a892017-05-18 17:28:27 +01004317 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4318 throws Exception {
4319 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004320 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004321
Rubin Xu19854862019-08-15 16:37:23 +01004322 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4323 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004324 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004325
Rubin Xucc391c22018-01-02 20:37:35 +00004326 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4327 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004328 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004329 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4330 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004331 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004332 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4333 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004334 // userId, if the password checkpoint value changes.
4335 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4336 MockUtils.checkIntentAction(
4337 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4338 MockUtils.checkUserHandle(userHandle));
4339 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004340 MockUtils.checkIntentAction(
4341 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4342 MockUtils.checkUserHandle(userHandle));
4343
Pavel Grafov75c0a892017-05-18 17:28:27 +01004344 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4345 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004346 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004347
4348 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4349 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004350 MockUtils.checkUserHandle(userHandle),
4351 eq(null),
4352 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004353
4354 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4355 // let it finish with system uid, otherwise it will throw and crash.
4356 flushTasks();
4357
4358 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004359 }
4360
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004361 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4362 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4363 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4364 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4365 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4366 DpmMockContext.SYSTEM_UID);
4367 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4368 DpmMockContext.SYSTEM_UID);
4369
4370 // Set up a device owner.
4371 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004372 setupDeviceOwner();
4373
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004374 // First and second user set IMEs manually.
4375 mContext.binder.callingUid = firstUserSystemUid;
4376 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4377 mContext.binder.callingUid = secondUserSystemUid;
4378 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004379
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004380 // Device owner changes IME for first user.
4381 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004382 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004383 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004384 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004385 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004386 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004387 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004388 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4389 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 // Second user changes IME manually.
4395 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4396 mContext.binder.callingUid = firstUserSystemUid;
4397 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4398 mContext.binder.callingUid = secondUserSystemUid;
4399 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004400
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004401 // First user changes IME manually.
4402 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4403 mContext.binder.callingUid = firstUserSystemUid;
4404 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4405 mContext.binder.callingUid = secondUserSystemUid;
4406 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004407
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004408 // Device owner changes IME for first user again.
4409 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004410 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004411 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004412 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004413 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004414 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004415 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4416 mContext.binder.callingUid = firstUserSystemUid;
4417 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4418 mContext.binder.callingUid = secondUserSystemUid;
4419 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004420
4421 // Restarting the DPMS should not lose information.
4422 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004423 mContext.binder.callingUid = firstUserSystemUid;
4424 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4425 mContext.binder.callingUid = secondUserSystemUid;
4426 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004427
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004428 // Device owner can find out whether it set the current IME itself.
4429 mContext.binder.callingUid = deviceOwnerUid;
4430 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004431
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004432 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004433 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004434 mContext.binder.callingUid = firstUserSystemUid;
4435 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4436 mContext.binder.callingUid = secondUserSystemUid;
4437 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004438 }
4439
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004440 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4441 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4442 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4443 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4444 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4445 DpmMockContext.SYSTEM_UID);
4446 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4447 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004448
4449 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004450 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004451 setupProfileOwner();
4452
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004453 // First and second user set IMEs manually.
4454 mContext.binder.callingUid = firstUserSystemUid;
4455 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4456 mContext.binder.callingUid = secondUserSystemUid;
4457 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004458
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004459 // Profile owner changes IME for second user.
4460 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004461 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004462 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004463 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004464 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004465 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004466 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004467 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4468 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 // First user changes IME manually.
4474 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4475 mContext.binder.callingUid = firstUserSystemUid;
4476 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4477 mContext.binder.callingUid = secondUserSystemUid;
4478 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004479
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004480 // Second user changes IME manually.
4481 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4482 mContext.binder.callingUid = firstUserSystemUid;
4483 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4484 mContext.binder.callingUid = secondUserSystemUid;
4485 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004486
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004487 // Profile owner changes IME for second user again.
4488 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004489 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004490 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004491 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004492 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004493 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004494 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4495 mContext.binder.callingUid = firstUserSystemUid;
4496 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4497 mContext.binder.callingUid = secondUserSystemUid;
4498 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004499
4500 // Restarting the DPMS should not lose information.
4501 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004502 mContext.binder.callingUid = firstUserSystemUid;
4503 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4504 mContext.binder.callingUid = secondUserSystemUid;
4505 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004506
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004507 // Profile owner can find out whether it set the current IME itself.
4508 mContext.binder.callingUid = profileOwnerUid;
4509 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004510
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004511 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004512 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004513 mContext.binder.callingUid = firstUserSystemUid;
4514 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4515 mContext.binder.callingUid = secondUserSystemUid;
4516 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004517 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004518
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004519 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4520 throws Exception {
4521 // Set up a device owner.
4522 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4523 setupDeviceOwner();
4524 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4525 }
4526
4527 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4528 throws Exception {
4529 // Set up a profile owner.
4530 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4531 setupProfileOwner();
4532 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4533 }
4534
4535 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4536 int adminUid) throws Exception {
4537 mContext.binder.callingUid = adminUid;
4538 final int userId = UserHandle.getUserId(adminUid);
4539
4540 final String packageName = "some.package";
4541 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4542 admin1, Collections.singletonList(packageName)));
4543 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4544
4545 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4546 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4547
4548 // Attempt to set to empty list (which means no listener is whitelisted)
4549 mContext.binder.callingUid = adminUid;
4550 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004551 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004552 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4553
4554 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4555 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4556 }
4557
4558 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4559 // Set up a managed profile
4560 final int MANAGED_PROFILE_USER_ID = 15;
4561 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4562 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4563 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4564
4565 final String permittedListener = "some.package";
4566 setupPackageInPackageManager(
4567 permittedListener,
4568 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4569 /*appId=*/ 12345, /*flags=*/ 0);
4570
4571 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4572 admin1, Collections.singletonList(permittedListener)));
4573
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004574 // isNotificationListenerServicePermitted should throw if not called from System.
4575 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4576 () -> dpms.isNotificationListenerServicePermitted(
4577 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004578
4579 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4580 assertTrue(dpms.isNotificationListenerServicePermitted(
4581 permittedListener, MANAGED_PROFILE_USER_ID));
4582 }
4583
4584 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4585 throws Exception {
4586 // Set up a managed profile
4587 final int MANAGED_PROFILE_USER_ID = 15;
4588 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4589 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4590 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4591
4592 final String permittedListener = "permitted.package";
4593 int appId = 12345;
4594 setupPackageInPackageManager(
4595 permittedListener,
4596 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4597 appId, /*flags=*/ 0);
4598
4599 final String notPermittedListener = "not.permitted.package";
4600 setupPackageInPackageManager(
4601 notPermittedListener,
4602 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4603 ++appId, /*flags=*/ 0);
4604
4605 final String systemListener = "system.package";
4606 setupPackageInPackageManager(
4607 systemListener,
4608 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4609 ++appId, ApplicationInfo.FLAG_SYSTEM);
4610
4611 // By default all packages are allowed
4612 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4613
4614 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4615 assertTrue(dpms.isNotificationListenerServicePermitted(
4616 permittedListener, MANAGED_PROFILE_USER_ID));
4617 assertTrue(dpms.isNotificationListenerServicePermitted(
4618 notPermittedListener, MANAGED_PROFILE_USER_ID));
4619 assertTrue(dpms.isNotificationListenerServicePermitted(
4620 systemListener, MANAGED_PROFILE_USER_ID));
4621
4622 // Setting only one package in the whitelist
4623 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4624 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4625 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004626 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004627 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4628 assertEquals(1, permittedListeners.size());
4629 assertEquals(permittedListener, permittedListeners.get(0));
4630
4631 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4632 assertTrue(dpms.isNotificationListenerServicePermitted(
4633 permittedListener, MANAGED_PROFILE_USER_ID));
4634 assertFalse(dpms.isNotificationListenerServicePermitted(
4635 notPermittedListener, MANAGED_PROFILE_USER_ID));
4636 // System packages are always allowed (even if not in the whitelist)
4637 assertTrue(dpms.isNotificationListenerServicePermitted(
4638 systemListener, MANAGED_PROFILE_USER_ID));
4639
4640 // Setting an empty whitelist - only system listeners allowed
4641 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4642 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004643 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004644 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4645
4646 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4647 assertFalse(dpms.isNotificationListenerServicePermitted(
4648 permittedListener, MANAGED_PROFILE_USER_ID));
4649 assertFalse(dpms.isNotificationListenerServicePermitted(
4650 notPermittedListener, MANAGED_PROFILE_USER_ID));
4651 // System packages are always allowed (even if not in the whitelist)
4652 assertTrue(dpms.isNotificationListenerServicePermitted(
4653 systemListener, MANAGED_PROFILE_USER_ID));
4654
4655 // Setting a null whitelist - all listeners allowed
4656 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4657 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4658 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4659
4660 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4661 assertTrue(dpms.isNotificationListenerServicePermitted(
4662 permittedListener, MANAGED_PROFILE_USER_ID));
4663 assertTrue(dpms.isNotificationListenerServicePermitted(
4664 notPermittedListener, MANAGED_PROFILE_USER_ID));
4665 assertTrue(dpms.isNotificationListenerServicePermitted(
4666 systemListener, MANAGED_PROFILE_USER_ID));
4667 }
4668
4669 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4670 throws Exception {
4671 // Set up a managed profile
4672 final int MANAGED_PROFILE_USER_ID = 15;
4673 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4674 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4675 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4676
4677 final String nonSystemPackage = "non.system.package";
4678 int appId = 12345;
4679 setupPackageInPackageManager(
4680 nonSystemPackage,
4681 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4682 appId, /*flags=*/ 0);
4683
4684 final String systemListener = "system.package";
4685 setupPackageInPackageManager(
4686 systemListener,
4687 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4688 ++appId, ApplicationInfo.FLAG_SYSTEM);
4689
4690 // By default all packages are allowed (for all profiles)
4691 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4692
4693 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4694 assertTrue(dpms.isNotificationListenerServicePermitted(
4695 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4696 assertTrue(dpms.isNotificationListenerServicePermitted(
4697 systemListener, MANAGED_PROFILE_USER_ID));
4698 assertTrue(dpms.isNotificationListenerServicePermitted(
4699 nonSystemPackage, UserHandle.USER_SYSTEM));
4700 assertTrue(dpms.isNotificationListenerServicePermitted(
4701 systemListener, UserHandle.USER_SYSTEM));
4702
4703 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4704 // all allowed in primary profile
4705 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4706 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004707 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004708 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4709
4710 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4711 assertFalse(dpms.isNotificationListenerServicePermitted(
4712 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4713 assertTrue(dpms.isNotificationListenerServicePermitted(
4714 systemListener, MANAGED_PROFILE_USER_ID));
4715 assertTrue(dpms.isNotificationListenerServicePermitted(
4716 nonSystemPackage, UserHandle.USER_SYSTEM));
4717 assertTrue(dpms.isNotificationListenerServicePermitted(
4718 systemListener, UserHandle.USER_SYSTEM));
4719 }
4720
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004721 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004722 mServiceContext.packageName = mRealTestContext.getPackageName();
4723 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4724 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004725 setDeviceOwner();
4726
Pavel Grafov75c0a892017-05-18 17:28:27 +01004727 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004728 }
4729
4730 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004731 mServiceContext.packageName = mRealTestContext.getPackageName();
4732 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4733 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004734 setAsProfileOwner(admin1);
4735
Pavel Grafov75c0a892017-05-18 17:28:27 +01004736 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4737 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004738 }
4739
4740 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004741 mServiceContext.packageName = mRealTestContext.getPackageName();
4742 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4743 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004744 setAsProfileOwner(admin1);
4745
Pavel Grafov75c0a892017-05-18 17:28:27 +01004746 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4747 caller.packageName = "com.example.delegate";
4748 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4749 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004750
Pavel Grafov75c0a892017-05-18 17:28:27 +01004751 // Make caller a delegated cert installer.
4752 runAsCaller(mAdmin1Context, dpms,
4753 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004754
4755 verifyCanGetOwnerInstalledCaCerts(null, caller);
4756 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004757 }
4758
Rubin Xucc391c22018-01-02 20:37:35 +00004759 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004760 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4761 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004762 Bundle restriction = new Bundle();
4763 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4764
4765 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4766 RestrictionsListener listener = new RestrictionsListener(mContext);
4767 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4768 new Bundle());
4769 verifyDataSharingChangedBroadcast();
4770 }
4771
4772 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004773 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4774 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004775 Bundle restriction = new Bundle();
4776 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4777
4778 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4779 RestrictionsListener listener = new RestrictionsListener(mContext);
4780 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4781 restriction);
4782 verifyDataSharingChangedBroadcast();
4783 }
4784
4785 public void testDisallowSharingIntoProfileUnchanged() {
4786 RestrictionsListener listener = new RestrictionsListener(mContext);
4787 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4788 new Bundle());
4789 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4790 }
4791
4792 private void verifyDataSharingChangedBroadcast() {
4793 Intent expectedIntent = new Intent(
4794 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4795 expectedIntent.setPackage("com.android.managedprovisioning");
4796 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4797 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4798 MockUtils.checkIntent(expectedIntent),
4799 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4800 }
4801
yuemingwe3d9c092018-01-11 12:11:44 +00004802 public void testOverrideApnAPIsFailWithPO() throws Exception {
4803 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004804 ApnSetting apn = (new ApnSetting.Builder())
4805 .setApnName("test")
4806 .setEntryName("test")
4807 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4808 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004809 assertExpectException(SecurityException.class, null, () ->
4810 dpm.addOverrideApn(admin1, apn));
4811 assertExpectException(SecurityException.class, null, () ->
4812 dpm.updateOverrideApn(admin1, 0, apn));
4813 assertExpectException(SecurityException.class, null, () ->
4814 dpm.removeOverrideApn(admin1, 0));
4815 assertExpectException(SecurityException.class, null, () ->
4816 dpm.getOverrideApns(admin1));
4817 assertExpectException(SecurityException.class, null, () ->
4818 dpm.setOverrideApnsEnabled(admin1, false));
4819 assertExpectException(SecurityException.class, null, () ->
4820 dpm.isOverrideApnEnabled(admin1));
4821 }
4822
Robin Lee2c68dad2017-03-17 12:50:24 +00004823 private void verifyCanGetOwnerInstalledCaCerts(
4824 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004825 final String alias = "cert";
4826 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004827
4828 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004829 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004830 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4831 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004832 }
4833 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4834
4835 // caller: device admin or delegated certificate installer
4836 callerContext.applicationInfo = new ApplicationInfo();
4837 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4838
4839 // system_server
4840 final DpmMockContext serviceContext = mContext;
4841 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004842 getServices().addPackageContext(callerUser, admin1Context);
4843 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004844
4845 // Install a CA cert.
4846 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004847 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004848 .thenReturn(alias);
4849 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004850 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004851 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004852 });
4853
Pavel Grafov75c0a892017-05-18 17:28:27 +01004854 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4855 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4856 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004857 flushTasks();
4858
Robin Lee2c68dad2017-03-17 12:50:24 +00004859 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4860
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004861 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004862 runAsCaller(admin1Context, dpms, (dpm) -> {
4863 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004864 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004865 ownerInstalledCaCerts.addAll(installedCaCerts);
4866 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004867
4868 // Restarting the DPMS should not lose information.
4869 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004870 runAsCaller(admin1Context, dpms, (dpm) ->
4871 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004872
4873 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004874 runAsCaller(serviceContext, dpms, (dpm) -> {
4875 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004876
Robin Lee2c68dad2017-03-17 12:50:24 +00004877 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004878 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004879 });
4880
Pavel Grafov75c0a892017-05-18 17:28:27 +01004881 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4882 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4883 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004884 flushTasks();
4885
4886 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4887 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004888 runAsCaller(admin1Context, dpms, (dpm) -> {
4889 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4890 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004891 }
4892
Robin Lee2c68dad2017-03-17 12:50:24 +00004893 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4894 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004895 final String alias = "cert";
4896 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004897
4898 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004899 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004900 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4901 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004902 }
4903 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4904
4905 // caller: device admin or delegated certificate installer
4906 callerContext.applicationInfo = new ApplicationInfo();
4907 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4908
4909 // system_server
4910 final DpmMockContext serviceContext = mContext;
4911 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004912 getServices().addPackageContext(callerUser, admin1Context);
4913 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004914
4915 // Install a CA cert as caller
4916 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004917 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004918 .thenReturn(alias);
4919 assertTrue(dpm.installCaCert(callerName, caCert));
4920 });
4921
4922 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004923 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004924 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004925 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4926 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4927 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004928 flushTasks();
4929
Robin Lee2c68dad2017-03-17 12:50:24 +00004930 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01004931 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00004932
4933 runAsCaller(serviceContext, dpms, (dpm) -> {
4934 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4935 assertNotNull(ownerInstalledCaCerts);
4936 assertTrue(ownerInstalledCaCerts.isEmpty());
4937 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004938 }
4939
Eran Messeri94d56762017-12-21 20:50:54 +00004940 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
4941 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
4942 Arrays.sort(gotFlags);
4943 Arrays.sort(expectedFlags);
4944 assertTrue(Arrays.equals(expectedFlags, gotFlags));
4945 }
4946
4947 public void testTranslationOfIdAttestationFlag() {
4948 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
4949 int[] correspondingAttUtilsTypes = new int[]{
4950 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
4951 AttestationUtils.ID_TYPE_MEID};
4952
4953 // Test translation of zero flags
4954 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
4955
4956 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
4957 // non-null array
4958 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
4959
4960 // Test translation of a single flag
4961 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
4962 new int[] {AttestationUtils.ID_TYPE_SERIAL});
4963 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
4964
4965 // Test translation of two flags
4966 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
4967 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
4968 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
4969 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
4970
4971 // Test translation of all three flags
4972 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
4973 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4974 AttestationUtils.ID_TYPE_MEID});
4975 // Test translation of all three flags
4976 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
4977 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
4978 AttestationUtils.ID_TYPE_MEID});
4979 }
4980
arangelov08d534b2018-01-22 15:20:53 +00004981 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
4982 setDeviceOwner();
4983 initializeDpms();
4984 assertFalse(getMockTransferMetadataManager().metadataFileExists());
4985 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
4986 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
4987 }
4988
4989 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
4990 DpmTestUtils.writeInputStreamToFile(
4991 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
4992 getDeviceOwnerPoliciesFile());
4993 DpmTestUtils.writeInputStreamToFile(
4994 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
4995 getDeviceOwnerFile());
4996 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
4997 }
4998
4999 public void testRevertDeviceOwnership_deviceNotMigrated()
5000 throws Exception {
5001 DpmTestUtils.writeInputStreamToFile(
5002 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5003 getDeviceOwnerPoliciesFile());
5004 DpmTestUtils.writeInputStreamToFile(
5005 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5006 getDeviceOwnerFile());
5007 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5008 }
5009
5010 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5011 throws Exception {
5012 DpmTestUtils.writeInputStreamToFile(
5013 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5014 getDeviceOwnerPoliciesFile());
5015 DpmTestUtils.writeInputStreamToFile(
5016 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5017 getDeviceOwnerFile());
5018 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5019 }
5020
5021 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5022 setupProfileOwner();
5023 initializeDpms();
5024 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5025 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5026 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5027 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5028 }
5029
5030 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5031 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5032 UserHandle.USER_SYSTEM);
5033 DpmTestUtils.writeInputStreamToFile(
5034 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5035 getProfileOwnerPoliciesFile());
5036 DpmTestUtils.writeInputStreamToFile(
5037 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5038 getProfileOwnerFile());
5039 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5040 }
5041
5042 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5043 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5044 UserHandle.USER_SYSTEM);
5045 DpmTestUtils.writeInputStreamToFile(
5046 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5047 getProfileOwnerPoliciesFile());
5048 DpmTestUtils.writeInputStreamToFile(
5049 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5050 getProfileOwnerFile());
5051 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5052 }
5053
5054 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5055 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5056 UserHandle.USER_SYSTEM);
5057 DpmTestUtils.writeInputStreamToFile(
5058 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5059 getProfileOwnerPoliciesFile());
5060 DpmTestUtils.writeInputStreamToFile(
5061 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5062 getProfileOwnerFile());
5063 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5064 }
5065
Eran Messeribb271892018-10-17 18:27:50 +01005066 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5067 setupProfileOwner();
5068 configureContextForAccess(mContext, false);
5069
5070 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005071 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005072 }
5073
5074 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5075 setupProfileOwner();
5076 configureContextForAccess(mContext, false);
5077
5078 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri518a01a2019-03-14 09:38:21 +00005079 () -> dpm.setProfileOwnerCanAccessDeviceIds(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005080 }
5081
5082 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5083 setupProfileOwner();
5084
5085 // This method will throw if the system context could not call
5086 // setProfileOwnerCanAccessDeviceIds successfully.
5087 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5088 }
5089
5090 private static void configureContextForAccess(DpmMockContext context, boolean granted) {
5091 when(context.spiedContext.checkCallingPermission(
5092 android.Manifest.permission.GRANT_PROFILE_OWNER_DEVICE_IDS_ACCESS))
5093 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5094 : PackageManager.PERMISSION_DENIED);
5095 }
5096
5097 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5098 setupProfileOwner();
5099
5100 final long ident = mServiceContext.binder.clearCallingIdentity();
5101 configureContextForAccess(mServiceContext, true);
5102
5103 mServiceContext.binder.callingUid =
5104 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5105 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5106 try {
5107 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005108 dpm.setProfileOwnerCanAccessDeviceIds(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005109 });
5110 } finally {
5111 mServiceContext.binder.restoreCallingIdentity(ident);
5112 }
5113 }
5114
5115 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5116 throws Exception {
5117 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5118 setupDeviceOwner();
5119 configureContextForAccess(mContext, false);
5120
5121 // Device owner should be allowed to request Device ID attestation.
5122 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5123 DpmMockContext.CALLER_SYSTEM_USER_UID);
5124
5125 // Another package must not be allowed to request Device ID attestation.
5126 assertExpectException(SecurityException.class, null,
5127 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5128 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5129 // Another component that is not the admin must not be allowed to request Device ID
5130 // attestation.
5131 assertExpectException(SecurityException.class, null,
5132 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5133 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5134 }
5135
5136 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5137 throws Exception {
5138 configureContextForAccess(mContext, false);
5139
5140 // Make sure a security exception is thrown if the device has no profile owner.
5141 assertExpectException(SecurityException.class, null,
5142 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5143 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5144
5145 setupProfileOwner();
5146 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5147
5148 // The profile owner is allowed to request Device ID attestation.
5149 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5150 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5151 DpmMockContext.CALLER_UID);
5152 // But not another package.
5153 assertExpectException(SecurityException.class, null,
5154 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5155 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5156 // Or another component which is not the admin.
5157 assertExpectException(SecurityException.class, null,
5158 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5159 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5160 }
5161
5162 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5163 final long ident = mServiceContext.binder.clearCallingIdentity();
5164
5165 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5166 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5167 try {
5168 runAsCaller(mServiceContext, dpms, action);
5169 } finally {
5170 mServiceContext.binder.restoreCallingIdentity(ident);
5171 }
5172 }
5173
5174 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5175 setupProfileOwner();
5176 markDelegatedCertInstallerAsInstalled();
5177
5178 // Configure a delegated cert installer.
5179 runAsCaller(mServiceContext, dpms,
5180 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5181 Arrays.asList(DELEGATION_CERT_INSTALL)));
5182
5183 configureProfileOwnerForDeviceIdAccess(admin1, DpmMockContext.CALLER_USER_HANDLE);
5184
5185 // Make sure that the profile owner can still request Device ID attestation.
5186 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5187 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5188 DpmMockContext.CALLER_UID);
5189
5190 runAsDelegatedCertInstaller(dpm -> {
5191 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5192 DpmMockContext.DELEGATE_PACKAGE_NAME,
5193 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5194 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5195 });
5196 }
5197
5198 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5199 throws Exception {
5200 setupProfileOwner();
5201 markDelegatedCertInstallerAsInstalled();
5202
5203 // Configure a delegated cert installer.
5204 runAsCaller(mServiceContext, dpms,
5205 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5206 Arrays.asList(DELEGATION_CERT_INSTALL)));
5207
5208
5209 assertExpectException(SecurityException.class, null,
5210 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5211 admin1.getPackageName(),
5212 DpmMockContext.CALLER_UID));
5213
5214 runAsDelegatedCertInstaller(dpm -> {
5215 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5216 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5217 DpmMockContext.DELEGATE_PACKAGE_NAME,
5218 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5219 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5220 });
5221 }
5222
Bernard Chaue9586552018-11-29 10:59:31 +00005223 public void testGetPasswordComplexity_securityExceptionIfParentInstance() {
5224 assertThrows(SecurityException.class,
5225 () -> new DevicePolicyManagerTestable(
5226 mServiceContext,
5227 dpms,
5228 /* parentInstance= */ true)
5229 .getPasswordComplexity());
5230 }
5231
5232 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5233 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5234 .thenReturn(false);
5235 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5236 }
5237
5238 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5239 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5240 .thenReturn(true);
5241 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5242 }
5243
5244
5245 public void testGetPasswordComplexity_currentUserNoPassword() {
5246 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5247 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005248 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005249 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5250 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5251
5252 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5253 }
5254
5255 public void testGetPasswordComplexity_currentUserHasPassword() {
5256 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5257 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005258 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005259 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5260 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005261 when(getServices().lockSettingsInternal
5262 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5263 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005264
5265 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5266 }
5267
5268 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5269 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5270 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005271 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005272
5273 UserInfo parentUser = new UserInfo();
5274 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5275 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5276 .thenReturn(parentUser.id);
5277
Rubin Xu19854862019-08-15 16:37:23 +01005278 when(getServices().lockSettingsInternal
5279 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
5280 .thenReturn(PasswordMetrics.computeForPassword("asdf".getBytes()));
5281 when(getServices().lockSettingsInternal
5282 .getUserPasswordMetrics(parentUser.id))
5283 .thenReturn(PasswordMetrics.computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005284
5285 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5286 }
5287
yuemingwd2bfbc82019-01-02 11:42:25 +00005288 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5289 setAsProfileOwner(admin1);
5290 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5291 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5292 }
5293
5294 public void testCrossProfileCalendarPackages_reopenDpms() {
5295 setAsProfileOwner(admin1);
5296 dpm.setCrossProfileCalendarPackages(admin1, null);
5297 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5298 assertTrue(packages == null);
5299 initializeDpms();
5300 packages = dpm.getCrossProfileCalendarPackages(admin1);
5301 assertTrue(packages == null);
5302
5303 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5304 packages = dpm.getCrossProfileCalendarPackages(admin1);
5305 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5306 initializeDpms();
5307 packages = dpm.getCrossProfileCalendarPackages(admin1);
5308 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5309
5310 final String dummyPackageName = "test";
5311 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5312 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5313 packages = dpm.getCrossProfileCalendarPackages(admin1);
5314 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5315 initializeDpms();
5316 packages = dpm.getCrossProfileCalendarPackages(admin1);
5317 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5318 }
5319
5320 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5321 assertTrue(expected != null);
5322 assertTrue(actual != null);
5323 assertTrue(expected.containsAll(actual));
5324 assertTrue(actual.containsAll(expected));
5325 }
5326
yuemingwdded98f2019-01-30 17:08:12 +00005327 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5328 setAsProfileOwner(admin1);
5329 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5330 when(getServices().settings.settingsSecureGetIntForUser(
5331 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5332 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5333 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5334 }
5335
5336 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5337 final String testPackage = "TEST_PACKAGE";
5338 setAsProfileOwner(admin1);
5339 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5340 when(getServices().settings.settingsSecureGetIntForUser(
5341 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5342 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5343 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5344 }
5345
5346 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5347 final String testPackage = "TEST_PACKAGE";
5348 setAsProfileOwner(admin1);
5349 dpm.setCrossProfileCalendarPackages(admin1, null);
5350 when(getServices().settings.settingsSecureGetIntForUser(
5351 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5352 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5353 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5354 }
5355
Eran Messeribb271892018-10-17 18:27:50 +01005356 private void configureProfileOwnerForDeviceIdAccess(ComponentName who, int userId) {
5357 final long ident = mServiceContext.binder.clearCallingIdentity();
5358 mServiceContext.binder.callingUid =
5359 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
5360 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri518a01a2019-03-14 09:38:21 +00005361 dpm.setProfileOwnerCanAccessDeviceIds(who);
Eran Messeribb271892018-10-17 18:27:50 +01005362 });
5363 mServiceContext.binder.restoreCallingIdentity(ident);
5364 }
5365
arangelov08d534b2018-01-22 15:20:53 +00005366 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5367 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5368 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5369 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5370
5371 final long ident = mServiceContext.binder.clearCallingIdentity();
5372 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5373 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5374 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5375 // To simulate a reboot, we just reinitialize dpms and call systemReady
5376 initializeDpms();
5377
5378 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5379 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5380 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5381 assertTrue(dpm.isAdminActive(admin1));
5382 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5383 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5384
5385 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5386 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5387 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5388 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5389
5390 mServiceContext.binder.restoreCallingIdentity(ident);
5391 }
5392
5393 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5394 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5395 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5396 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5397
5398 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5399 DpmMockContext.CALLER_SYSTEM_USER_UID);
5400 setUpPackageManagerForAdmin(admin1, uid);
5401 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5402 // To simulate a reboot, we just reinitialize dpms and call systemReady
5403 initializeDpms();
5404
5405 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5406 assertTrue(dpm.isAdminActive(admin1));
5407 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5408 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5409 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5410 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5411 }
5412
5413 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5414 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5415 metadataManager.deleteMetadataFile();
5416
5417 final TransferOwnershipMetadataManager.Metadata metadata =
5418 new TransferOwnershipMetadataManager.Metadata(
5419 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5420 callerUserHandle,
5421 adminType);
5422 metadataManager.saveMetadataFile(metadata);
5423 }
5424
5425 private File getDeviceOwnerFile() {
5426 return dpms.mOwners.getDeviceOwnerFile();
5427 }
5428
5429 private File getProfileOwnerFile() {
5430 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5431 }
5432
5433 private File getProfileOwnerPoliciesFile() {
5434 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5435 DpmMockContext.CALLER_USER_HANDLE);
5436 return getPoliciesFile(parentDir);
5437 }
5438
5439 private File getDeviceOwnerPoliciesFile() {
5440 return getPoliciesFile(getServices().systemUserDataDir);
5441 }
5442
5443 private File getPoliciesFile(File parentDir) {
5444 return new File(parentDir, "device_policies.xml");
5445 }
5446
5447 private InputStream getRawStream(@RawRes int id) {
5448 return mRealTestContext.getResources().openRawResource(id);
5449 }
5450
Victor Chang3e794af2016-03-04 13:48:17 +00005451 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005452 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005453 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5454 dpms.notifyChangeToContentObserver(
5455 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5456 }
5457
5458 private void assertProvisioningAllowed(String action, boolean expected) {
5459 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5460 dpm.isProvisioningAllowed(action));
5461 }
Tony Mak2f26b792016-11-28 17:54:51 +00005462
Nicolas Prevot45d29072017-01-18 16:11:19 +00005463 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5464 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005465 final String previousPackageName = mContext.packageName;
5466 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005467
5468 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5469 mContext.packageName = packageName;
5470 mMockContext.binder.callingUid = uid;
5471 assertProvisioningAllowed(action, expected);
5472
5473 // Set the previous package name / calling uid to go back to the initial state.
5474 mContext.packageName = previousPackageName;
5475 mMockContext.binder.callingUid = previousUid;
5476 }
5477
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005478 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005479 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5480 }
5481
5482 private void assertCheckProvisioningPreCondition(
5483 String action, String packageName, int provisioningCondition) {
5484 assertEquals("checkProvisioningPreCondition("
5485 + action + ", " + packageName + ") returning unexpected result",
5486 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005487 }
5488
Tony Mak2f26b792016-11-28 17:54:51 +00005489 /**
5490 * Setup a managed profile with the specified admin and its uid.
5491 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5492 * @param adminUid uid of the admin package.
5493 * @param copyFromAdmin package information for {@code admin} will be built based on this
5494 * component's information.
5495 */
5496 private void addManagedProfile(
5497 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5498 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005499 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005500 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5501 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5502 dpm.setActiveAdmin(admin, false, userId);
5503 assertTrue(dpm.setProfileOwner(admin, null, userId));
5504 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5505 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005506
5507 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005508 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005509 */
Robin Leeabaa0692017-02-20 20:54:22 +00005510 private static StringParceledListSlice asSlice(String[] s) {
5511 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005512 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005513
5514 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005515 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5516 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005517
Robin Lee2c68dad2017-03-17 12:50:24 +00005518 // We can't let exceptions happen on the background thread. Throw them here if they happen
5519 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005520 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005521 }
Victor Chang3e794af2016-03-04 13:48:17 +00005522}