blob: b6ed22b83b4eaab4e739e4cb3dca7e89a4969a34 [file] [log] [blame]
Makoto Onukicc4bbeb2015-09-17 10:28:24 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070016package com.android.server.devicepolicy;
17
Pavel Grafov75c0a892017-05-18 17:28:27 +010018import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
19import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
Eran Messeri94d56762017-12-21 20:50:54 +000020import static android.app.admin.DevicePolicyManager.ID_TYPE_BASE_INFO;
21import static android.app.admin.DevicePolicyManager.ID_TYPE_IMEI;
22import static android.app.admin.DevicePolicyManager.ID_TYPE_MEID;
23import static android.app.admin.DevicePolicyManager.ID_TYPE_SERIAL;
Bernard Chaue9586552018-11-29 10:59:31 +000024import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_HIGH;
25import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_MEDIUM;
26import static android.app.admin.DevicePolicyManager.PASSWORD_COMPLEXITY_NONE;
yinxuf4f9cec2017-06-19 10:28:19 -070027import static android.app.admin.DevicePolicyManager.WIPE_EUICC;
Pavel Grafov6f334842019-08-06 14:37:06 +010028import static android.app.admin.PasswordMetrics.computeForPassword;
Pavel Grafov6a40f092016-10-25 15:46:51 +010029import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
30import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
31import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
32
Pavel Grafov6f334842019-08-06 14:37:06 +010033import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
Ram Periathiruvadi32d53552019-02-19 13:25:46 -080034import static com.android.internal.widget.LockPatternUtils.EscrowTokenStateChangeCallback;
Eugene Susla4f8680b2017-08-07 17:25:30 -070035import static com.android.server.testutils.TestUtils.assertExpectException;
Pavel Grafova1ea8d92017-05-25 21:55:24 +010036
Pavel Grafov75c0a892017-05-18 17:28:27 +010037import static org.mockito.Matchers.any;
38import static org.mockito.Matchers.anyInt;
39import static org.mockito.Matchers.anyLong;
40import static org.mockito.Matchers.anyObject;
41import static org.mockito.Matchers.anyString;
42import static org.mockito.Matchers.eq;
43import static org.mockito.Matchers.isNull;
44import static org.mockito.Mockito.atLeast;
Rubin Xu19854862019-08-15 16:37:23 +010045import static org.mockito.Mockito.atMost;
Pavel Grafov75c0a892017-05-18 17:28:27 +010046import static org.mockito.Mockito.doAnswer;
47import static org.mockito.Mockito.doReturn;
48import static org.mockito.Mockito.never;
49import static org.mockito.Mockito.nullable;
50import static org.mockito.Mockito.reset;
51import static org.mockito.Mockito.timeout;
52import static org.mockito.Mockito.times;
53import static org.mockito.Mockito.verify;
Sudheer Shanka101c3532018-01-08 16:28:42 -080054import static org.mockito.Mockito.verifyNoMoreInteractions;
Pavel Grafov75c0a892017-05-18 17:28:27 +010055import static org.mockito.Mockito.verifyZeroInteractions;
56import static org.mockito.Mockito.when;
57import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Bernard Chaue9586552018-11-29 10:59:31 +000058import static org.testng.Assert.assertThrows;
Pavel Grafov75c0a892017-05-18 17:28:27 +010059
Makoto Onukif76b06a2015-09-22 15:03:44 -070060import android.Manifest.permission;
arangelov08d534b2018-01-22 15:20:53 +000061import android.annotation.RawRes;
Makoto Onukif76b06a2015-09-22 15:03:44 -070062import android.app.Activity;
Jonathan Scott367ebf42019-05-16 15:13:17 +010063import android.app.AppOpsManager;
Robin Lee7f5c91c2017-02-08 21:27:02 +000064import android.app.Notification;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070065import android.app.admin.DeviceAdminReceiver;
66import android.app.admin.DevicePolicyManager;
67import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010068import android.app.admin.PasswordMetrics;
Neil Fullere3767562019-11-23 11:33:57 +000069import android.app.timedetector.ManualTimeSuggestion;
Makoto Onukif76b06a2015-09-22 15:03:44 -070070import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000072import android.content.Intent;
Rubin Xued1928a2016-02-11 17:23:06 +000073import android.content.pm.ApplicationInfo;
74import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import android.content.pm.PackageManager;
Benjamin Franz714f77b2017-08-01 14:18:35 +010076import android.content.pm.ResolveInfo;
Robin Leeabaa0692017-02-20 20:54:22 +000077import android.content.pm.StringParceledListSlice;
Tony Mak2f26b792016-11-28 17:54:51 +000078import android.content.pm.UserInfo;
Pavel Grafov75c0a892017-05-18 17:28:27 +010079import android.graphics.Color;
80import android.net.Uri;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080081import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070082import android.os.Bundle;
Makoto Onukic8a5a552015-11-19 14:29:12 -080083import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070084import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070085import android.os.UserManager;
Pavel Grafovc14b3172017-07-03 13:15:11 +010086import android.platform.test.annotations.Presubmit;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080087import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010088import android.security.KeyChain;
Eran Messeri94d56762017-12-21 20:50:54 +000089import android.security.keystore.AttestationUtils;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000090import android.telephony.TelephonyManager;
yuemingwe3d9c092018-01-11 12:11:44 +000091import android.telephony.data.ApnSetting;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080092import android.test.MoreAsserts;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010093import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070094import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070095
Pavel Grafov57f1b662019-03-27 14:55:38 +000096import androidx.test.filters.SmallTest;
97
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010098import com.android.internal.R;
Rubin Xua58125d2019-09-06 20:11:48 +010099import com.android.internal.widget.LockscreenCredential;
Alan Treadwayafad8782016-01-19 15:15:08 +0000100import com.android.server.LocalServices;
101import com.android.server.SystemService;
Rubin Xucc391c22018-01-02 20:37:35 +0000102import com.android.server.devicepolicy.DevicePolicyManagerService.RestrictionsListener;
Esteban Talavera6c9116a2016-11-24 16:12:44 +0000103import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +0000104
Robin Lee7f5c91c2017-02-08 21:27:02 +0000105import org.hamcrest.BaseMatcher;
106import org.hamcrest.Description;
Sudheer Shanka101c3532018-01-08 16:28:42 -0800107import org.mockito.Mockito;
Makoto Onukib643fb02015-09-22 15:03:44 -0700108import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700109
arangelov08d534b2018-01-22 15:20:53 +0000110import java.io.File;
111import java.io.InputStream;
Makoto Onukic8a5a552015-11-19 14:29:12 -0800112import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +0000113import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +0000114import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -0700115import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700116import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -0700117import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +0100118import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +0000119import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700121/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700122 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000123 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 m FrameworksServicesTests &&
125 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000126 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700127 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Brett Chabota26eda92018-07-23 13:08:30 -0700128 -w com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700129
130 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000131 *
132 * , or:
133 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700134 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000135@SmallTest
Pavel Grafovc14b3172017-07-03 13:15:11 +0100136@Presubmit
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700137public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000138 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
139 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
140 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100141 public static final String NOT_DEVICE_OWNER_MSG = "does not own the device";
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800142 public static final String NOT_PROFILE_OWNER_MSG = "does not own the profile";
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100143 public static final String ONGOING_CALL_MSG = "ongoing call on the device";
Alan Treadwayafad8782016-01-19 15:15:08 +0000144
Pavel Grafov75c0a892017-05-18 17:28:27 +0100145 // TODO replace all instances of this with explicit {@link #mServiceContext}.
146 @Deprecated
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700147 private DpmMockContext mContext;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100148
149 private DpmMockContext mServiceContext;
150 private DpmMockContext mAdmin1Context;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700151 public DevicePolicyManager dpm;
152 public DevicePolicyManagerServiceTestable dpms;
153
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100154 /*
155 * The CA cert below is the content of cacert.pem as generated by:
156 *
157 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
158 */
159 private static final String TEST_CA =
160 "-----BEGIN CERTIFICATE-----\n" +
161 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
162 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
163 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
164 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
165 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
166 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
167 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
168 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
169 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
170 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
171 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
172 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
173 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
174 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
175 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
176 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
177 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
178 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
179 "wQ==\n" +
180 "-----END CERTIFICATE-----\n";
181
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700182 @Override
183 protected void setUp() throws Exception {
184 super.setUp();
185
186 mContext = getContext();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100187 mServiceContext = mContext;
188 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
189 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700190 .thenReturn(true);
Benjamin Franz714f77b2017-08-01 14:18:35 +0100191 doReturn(Collections.singletonList(new ResolveInfo()))
192 .when(getServices().packageManager).queryBroadcastReceiversAsUser(
193 any(Intent.class),
194 anyInt(),
195 any(UserHandle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700196
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800197 // By default, pretend all users are running and unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100198 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800199
Makoto Onukia52562c2015-10-01 16:12:31 -0700200 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700201
Sudheer Shanka101c3532018-01-08 16:28:42 -0800202 Mockito.reset(getServices().usageStatsManagerInternal);
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800203 Mockito.reset(getServices().networkPolicyManagerInternal);
Makoto Onukid932f762015-09-29 16:53:38 -0700204 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
205 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
206 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800207 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700208
Pavel Grafov75c0a892017-05-18 17:28:27 +0100209 mAdmin1Context = new DpmMockContext(getServices(), mRealTestContext);
210 mAdmin1Context.packageName = admin1.getPackageName();
211 mAdmin1Context.applicationInfo = new ApplicationInfo();
212 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
213
Makoto Onukib643fb02015-09-22 15:03:44 -0700214 setUpUserManager();
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100215
216 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700217 }
218
arangelov08d534b2018-01-22 15:20:53 +0000219 private TransferOwnershipMetadataManager getMockTransferMetadataManager() {
220 return dpms.mTransferOwnershipMetadataManager;
221 }
222
Robin Lee2c68dad2017-03-17 12:50:24 +0000223 @Override
224 protected void tearDown() throws Exception {
225 flushTasks();
arangelov08d534b2018-01-22 15:20:53 +0000226 getMockTransferMetadataManager().deleteMetadataFile();
Robin Lee2c68dad2017-03-17 12:50:24 +0000227 super.tearDown();
228 }
229
Makoto Onukia52562c2015-10-01 16:12:31 -0700230 private void initializeDpms() {
231 // Need clearCallingIdentity() to pass permission checks.
232 final long ident = mContext.binder.clearCallingIdentity();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100233 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Makoto Onukia52562c2015-10-01 16:12:31 -0700234
Pavel Grafov75c0a892017-05-18 17:28:27 +0100235 dpms = new DevicePolicyManagerServiceTestable(getServices(), mContext);
236 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
237 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
Makoto Onukia52562c2015-10-01 16:12:31 -0700238
Pavel Grafov75c0a892017-05-18 17:28:27 +0100239 dpm = new DevicePolicyManagerTestable(mContext, dpms);
Makoto Onukia52562c2015-10-01 16:12:31 -0700240
Pavel Grafov75c0a892017-05-18 17:28:27 +0100241 mContext.binder.restoreCallingIdentity(ident);
Makoto Onukia52562c2015-10-01 16:12:31 -0700242 }
243
Makoto Onukib643fb02015-09-22 15:03:44 -0700244 private void setUpUserManager() {
245 // Emulate UserManager.set/getApplicationRestriction().
246 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
247
248 // UM.setApplicationRestrictions() will save to appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000249 doAnswer((Answer<Void>) invocation -> {
250 String pkg = (String) invocation.getArguments()[0];
251 Bundle bundle = (Bundle) invocation.getArguments()[1];
252 UserHandle user = (UserHandle) invocation.getArguments()[2];
Makoto Onukib643fb02015-09-22 15:03:44 -0700253
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000254 appRestrictions.put(Pair.create(pkg, user), bundle);
Makoto Onukib643fb02015-09-22 15:03:44 -0700255
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000256 return null;
Pavel Grafov75c0a892017-05-18 17:28:27 +0100257 }).when(getServices().userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100258 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700259
260 // UM.getApplicationRestrictions() will read from appRestrictions.
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000261 doAnswer((Answer<Bundle>) invocation -> {
262 String pkg = (String) invocation.getArguments()[0];
263 UserHandle user = (UserHandle) invocation.getArguments()[1];
Makoto Onukib643fb02015-09-22 15:03:44 -0700264
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +0000265 return appRestrictions.get(Pair.create(pkg, user));
Pavel Grafov75c0a892017-05-18 17:28:27 +0100266 }).when(getServices().userManager).getApplicationRestrictions(
Makoto Onukib643fb02015-09-22 15:03:44 -0700267 anyString(), any(UserHandle.class));
268
Makoto Onukid932f762015-09-29 16:53:38 -0700269 // Add the first secondary user.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100270 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700271 }
272
273 private void setAsProfileOwner(ComponentName admin) {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100274 final long ident = mServiceContext.binder.clearCallingIdentity();
Makoto Onukib643fb02015-09-22 15:03:44 -0700275
Pavel Grafov75c0a892017-05-18 17:28:27 +0100276 mServiceContext.binder.callingUid =
277 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
278 runAsCaller(mServiceContext, dpms, dpm -> {
279 // PO needs to be a DA.
280 dpm.setActiveAdmin(admin, /*replace=*/ false);
281 // Fire!
282 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
283 // Check
284 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
285 });
Makoto Onukib643fb02015-09-22 15:03:44 -0700286
Pavel Grafov75c0a892017-05-18 17:28:27 +0100287 mServiceContext.binder.restoreCallingIdentity(ident);
Makoto Onukib643fb02015-09-22 15:03:44 -0700288 }
289
290 public void testHasNoFeature() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +0100291 when(getServices().packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700292 .thenReturn(false);
293
294 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
Pavel Grafov75c0a892017-05-18 17:28:27 +0100295 new DevicePolicyManagerServiceTestable(getServices(), mContext);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700296
297 // If the device has no DPMS feature, it shouldn't register the local service.
298 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
299 }
300
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800301 public void testLoadAdminData() throws Exception {
Sudheer Shanka101c3532018-01-08 16:28:42 -0800302 // Device owner in SYSTEM_USER
303 setDeviceOwner();
304 // Profile owner in CALLER_USER_HANDLE
305 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
306 setAsProfileOwner(admin2);
307 // Active admin in CALLER_USER_HANDLE
308 final int ANOTHER_UID = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, 1306);
309 setUpPackageManagerForFakeAdmin(adminAnotherPackage, ANOTHER_UID, admin2);
310 dpm.setActiveAdmin(adminAnotherPackage, /* replace =*/ false,
311 DpmMockContext.CALLER_USER_HANDLE);
312 assertTrue(dpm.isAdminActiveAsUser(adminAnotherPackage,
313 DpmMockContext.CALLER_USER_HANDLE));
314
315 initializeDpms();
316
317 // Verify
318 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800319 MockUtils.checkApps(admin1.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800320 eq(UserHandle.USER_SYSTEM));
321 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800322 MockUtils.checkApps(admin2.getPackageName(),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800323 adminAnotherPackage.getPackageName()),
324 eq(DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800325 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
326 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
327 }
328
329 public void testLoadAdminData_noAdmins() throws Exception {
330 final int ANOTHER_USER_ID = 15;
331 getServices().addUser(ANOTHER_USER_ID, 0);
332
333 initializeDpms();
334
335 // Verify
336 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
337 null, DpmMockContext.CALLER_USER_HANDLE);
338 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
339 null, ANOTHER_USER_ID);
340 verify(getServices().usageStatsManagerInternal).onAdminDataAvailable();
341 verify(getServices().networkPolicyManagerInternal).onAdminDataAvailable();
Sudheer Shanka101c3532018-01-08 16:28:42 -0800342 }
343
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700344 /**
345 * Caller doesn't have proper permissions.
346 */
347 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700348 // 1. Failure cases.
349
350 // Caller doesn't have MANAGE_DEVICE_ADMINS.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100351 assertExpectException(SecurityException.class, /* messageRegex= */ null,
352 () -> dpm.setActiveAdmin(admin1, false));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700353
354 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
355 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100356
357 assertExpectException(SecurityException.class, /* messageRegex= */ null,
358 () -> dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700359 }
360
Makoto Onukif76b06a2015-09-22 15:03:44 -0700361 /**
362 * Test for:
363 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800364 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700365 * {@link DevicePolicyManager#isAdminActive}
366 * {@link DevicePolicyManager#isAdminActiveAsUser}
367 * {@link DevicePolicyManager#getActiveAdmins}
368 * {@link DevicePolicyManager#getActiveAdminsAsUser}
369 */
370 public void testSetActiveAdmin() throws Exception {
371 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700372 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
373
Makoto Onukif76b06a2015-09-22 15:03:44 -0700374 // 2. Call the API.
375 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700376
377 // 3. Verify internal calls.
378
379 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700380 verify(mContext.spiedContext).sendBroadcastAsUser(
381 MockUtils.checkIntentAction(
382 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
383 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
384 verify(mContext.spiedContext).sendBroadcastAsUser(
385 MockUtils.checkIntentAction(
386 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100387 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
388 eq(null),
389 any(Bundle.class));
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700390
Pavel Grafov75c0a892017-05-18 17:28:27 +0100391 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700392 eq(admin1.getPackageName()),
393 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
394 eq(PackageManager.DONT_KILL_APP),
395 eq(DpmMockContext.CALLER_USER_HANDLE),
396 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700397
Sudheer Shanka101c3532018-01-08 16:28:42 -0800398 verify(getServices().usageStatsManagerInternal).onActiveAdminAdded(
399 admin1.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
400
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700401 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700402
403 // Make sure it's active admin1.
404 assertTrue(dpm.isAdminActive(admin1));
405 assertFalse(dpm.isAdminActive(admin2));
406 assertFalse(dpm.isAdminActive(admin3));
407
408 // But not admin1 for a different user.
409
410 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
411 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
412 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
413
414 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
415 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
416
417 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
418
419 // Next, add one more admin.
420 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700421 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
Christine Franks361b8252017-06-23 18:12:46 -0700422 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700423
424 dpm.setActiveAdmin(admin2, /* replace =*/ false);
425
426 // Now we have two admins.
427 assertTrue(dpm.isAdminActive(admin1));
428 assertTrue(dpm.isAdminActive(admin2));
429 assertFalse(dpm.isAdminActive(admin3));
430
431 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
432 // again. (times(1) because it was previously called for admin1)
Pavel Grafov75c0a892017-05-18 17:28:27 +0100433 verify(getServices().ipackageManager, times(1)).setApplicationEnabledSetting(
Makoto Onukif76b06a2015-09-22 15:03:44 -0700434 eq(admin1.getPackageName()),
435 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
436 eq(PackageManager.DONT_KILL_APP),
437 eq(DpmMockContext.CALLER_USER_HANDLE),
438 anyString());
439
Sudheer Shanka101c3532018-01-08 16:28:42 -0800440 // times(2) because it was previously called for admin1 which is in the same package
441 // as admin2.
442 verify(getServices().usageStatsManagerInternal, times(2)).onActiveAdminAdded(
443 admin2.getPackageName(), DpmMockContext.CALLER_USER_HANDLE);
444
Makoto Onukif76b06a2015-09-22 15:03:44 -0700445 // 4. Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100446 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
447 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700448
449 // 5. Add the same admin1 again with replace, which should succeed.
450 dpm.setActiveAdmin(admin1, /* replace =*/ true);
451
452 // TODO make sure it's replaced.
453
454 // 6. Test getActiveAdmins()
455 List<ComponentName> admins = dpm.getActiveAdmins();
456 assertEquals(2, admins.size());
457 assertEquals(admin1, admins.get(0));
458 assertEquals(admin2, admins.get(1));
459
Sudheer Shanka101c3532018-01-08 16:28:42 -0800460 // There shouldn't be any callback to UsageStatsManagerInternal when the admin is being
461 // replaced
462 verifyNoMoreInteractions(getServices().usageStatsManagerInternal);
463
Makoto Onukif76b06a2015-09-22 15:03:44 -0700464 // Another user has no admins.
465 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
466
467 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
468 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
469
470 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
471 }
472
Makoto Onukid932f762015-09-29 16:53:38 -0700473 public void testSetActiveAdmin_multiUsers() throws Exception {
474
475 final int ANOTHER_USER_ID = 100;
476 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
477
Pavel Grafov75c0a892017-05-18 17:28:27 +0100478 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukid932f762015-09-29 16:53:38 -0700479
480 // Set up pacakge manager for the other user.
481 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700482
483 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
484
485 dpm.setActiveAdmin(admin1, /* replace =*/ false);
486
487 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
488 dpm.setActiveAdmin(admin2, /* replace =*/ false);
489
490
491 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
492 assertTrue(dpm.isAdminActive(admin1));
493 assertFalse(dpm.isAdminActive(admin2));
494
495 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
496 assertFalse(dpm.isAdminActive(admin1));
497 assertTrue(dpm.isAdminActive(admin2));
498 }
499
Makoto Onukif76b06a2015-09-22 15:03:44 -0700500 /**
501 * Test for:
502 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800503 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700504 */
505 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
506 // 1. Make sure the caller has proper permissions.
507 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
508
509 dpm.setActiveAdmin(admin1, /* replace =*/ false);
510 assertTrue(dpm.isAdminActive(admin1));
511
512 // Add the same admin1 again without replace, which should throw.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100513 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
514 () -> dpm.setActiveAdmin(admin1, /* replace =*/ false));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700515 }
516
517 /**
518 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800519 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
520 * BIND_DEVICE_ADMIN.
521 */
522 public void testSetActiveAdmin_permissionCheck() throws Exception {
523 // 1. Make sure the caller has proper permissions.
524 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
525
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100526 assertExpectException(IllegalArgumentException.class,
527 /* messageRegex= */ permission.BIND_DEVICE_ADMIN,
528 () -> dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false));
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800529 assertFalse(dpm.isAdminActive(adminNoPerm));
530
531 // Change the target API level to MNC. Now it can be set as DA.
532 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
533 VERSION_CODES.M);
534 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
535 assertTrue(dpm.isAdminActive(adminNoPerm));
536
537 // TODO Test the "load from the file" case where DA will still be loaded even without
538 // BIND_DEVICE_ADMIN and target API is N.
539 }
540
541 /**
542 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700543 * {@link DevicePolicyManager#removeActiveAdmin}
544 */
545 public void testRemoveActiveAdmin_SecurityException() {
546 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
547
548 // Add admin.
549
550 dpm.setActiveAdmin(admin1, /* replace =*/ false);
551
552 assertTrue(dpm.isAdminActive(admin1));
553
554 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
555
556 // Directly call the DPMS method with a different userid, which should fail.
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100557 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
558 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700559
560 // Try to remove active admin with a different caller userid should fail too, without
561 // having MANAGE_DEVICE_ADMINS.
562 mContext.callerPermissions.clear();
563
Makoto Onukid932f762015-09-29 16:53:38 -0700564 // Change the caller, and call into DPMS directly with a different user-id.
565
Makoto Onukif76b06a2015-09-22 15:03:44 -0700566 mContext.binder.callingUid = 1234567;
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100567 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
568 () -> dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700569 }
570
571 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800572 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
573 * (because we can't send the remove broadcast).
574 */
575 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
576 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
577
578 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
579
580 // Add admin.
581
582 dpm.setActiveAdmin(admin1, /* replace =*/ false);
583
584 assertTrue(dpm.isAdminActive(admin1));
585
586 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
587
588 // 1. User not unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100589 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800590 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100591 assertExpectException(IllegalStateException.class,
592 /* messageRegex= */ "User must be running and unlocked",
593 () -> dpm.removeActiveAdmin(admin1));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800594
595 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800596 verify(getServices().usageStatsManagerInternal, times(0)).setActiveAdminApps(
597 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800598
599 // 2. User unlocked.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100600 when(getServices().userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800601 .thenReturn(true);
602
603 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700604 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800605 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
606 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800607 }
608
609 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700610 * Test for:
611 * {@link DevicePolicyManager#removeActiveAdmin}
612 */
Makoto Onukid932f762015-09-29 16:53:38 -0700613 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700614 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
615
616 // Add admin1.
617
618 dpm.setActiveAdmin(admin1, /* replace =*/ false);
619
620 assertTrue(dpm.isAdminActive(admin1));
621 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
622
623 // Different user, but should work, because caller has proper permissions.
624 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700625
626 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700627 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700628
629 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700630 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800631 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
632 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700633
634 // TODO DO Still can't be removed in this case.
635 }
636
637 /**
638 * Test for:
639 * {@link DevicePolicyManager#removeActiveAdmin}
640 */
641 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
642 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
643 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
644
645 // Add admin1.
646
647 dpm.setActiveAdmin(admin1, /* replace =*/ false);
648
649 assertTrue(dpm.isAdminActive(admin1));
650 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
651
652 // Broadcast from saveSettingsLocked().
653 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
654 MockUtils.checkIntentAction(
655 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
656 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
657
658 // Remove. No permissions, but same user, so it'll work.
659 mContext.callerPermissions.clear();
660 dpm.removeActiveAdmin(admin1);
661
Makoto Onukif76b06a2015-09-22 15:03:44 -0700662 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
663 MockUtils.checkIntentAction(
664 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
665 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
666 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100667 eq(AppOpsManager.OP_NONE),
668 any(Bundle.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700669 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700670 eq(dpms.mHandler),
671 eq(Activity.RESULT_OK),
672 isNull(String.class),
673 isNull(Bundle.class));
674
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700675 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -0800676 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
677 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700678
679 // Again broadcast from saveSettingsLocked().
680 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
681 MockUtils.checkIntentAction(
682 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
683 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
684
685 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700686 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700687
Sudheer Shanka101c3532018-01-08 16:28:42 -0800688 public void testRemoveActiveAdmin_multipleAdminsInUser() {
689 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
690 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
691
692 // Add admin1.
693 dpm.setActiveAdmin(admin1, /* replace =*/ false);
694
695 assertTrue(dpm.isAdminActive(admin1));
696 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
697
698 // Add admin2.
699 dpm.setActiveAdmin(admin2, /* replace =*/ false);
700
701 assertTrue(dpm.isAdminActive(admin2));
702 assertFalse(dpm.isRemovingAdmin(admin2, DpmMockContext.CALLER_USER_HANDLE));
703
704 // Broadcast from saveSettingsLocked().
705 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
706 MockUtils.checkIntentAction(
707 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
708 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
709
710 // Remove. No permissions, but same user, so it'll work.
711 mContext.callerPermissions.clear();
712 dpm.removeActiveAdmin(admin1);
713
714 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
715 MockUtils.checkIntentAction(
716 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
717 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
718 isNull(String.class),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100719 eq(AppOpsManager.OP_NONE),
720 any(Bundle.class),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800721 any(BroadcastReceiver.class),
722 eq(dpms.mHandler),
723 eq(Activity.RESULT_OK),
724 isNull(String.class),
725 isNull(Bundle.class));
726
727 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
728 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800729 MockUtils.checkApps(admin2.getPackageName()),
Sudheer Shanka101c3532018-01-08 16:28:42 -0800730 eq(DpmMockContext.CALLER_USER_HANDLE));
731
732 // Again broadcast from saveSettingsLocked().
733 verify(mContext.spiedContext, times(3)).sendBroadcastAsUser(
734 MockUtils.checkIntentAction(
735 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
736 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
737 }
738
739 /**
740 * Test for:
741 * {@link DevicePolicyManager#forceRemoveActiveAdmin(ComponentName, int)}
742 */
743 public void testForceRemoveActiveAdmin() throws Exception {
744 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
745
746 // Add admin.
747 setupPackageInPackageManager(admin1.getPackageName(),
748 /* userId= */ DpmMockContext.CALLER_USER_HANDLE,
749 /* appId= */ 10138,
750 /* flags= */ ApplicationInfo.FLAG_TEST_ONLY);
751 dpm.setActiveAdmin(admin1, /* replace =*/ false);
752 assertTrue(dpm.isAdminActive(admin1));
753
754 // Calling from a non-shell uid should fail with a SecurityException
755 mContext.binder.callingUid = 123456;
756 assertExpectException(SecurityException.class,
757 /* messageRegex =*/ "Non-shell user attempted to call",
758 () -> dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
759
760 mContext.binder.callingUid = Process.SHELL_UID;
761 dpms.forceRemoveActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
762
763 mContext.callerPermissions.add(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
764 // Verify
765 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
766 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
767 null, DpmMockContext.CALLER_USER_HANDLE);
768 }
769
Makoto Onukib643fb02015-09-22 15:03:44 -0700770 /**
Alex Johnston9a6f4412019-09-16 16:05:18 +0100771 * Test for: {@link DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)}
772 *
773 * Validates that when the password history length is set, it is persisted after rebooting
774 */
775 public void testSaveAndLoadPasswordHistoryLength_persistedAfterReboot() throws Exception {
776 int passwordHistoryLength = 2;
777
778 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
779 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
780 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
781
782 // Install admin1 on system user.
783 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
784
785 // Set admin1 to active admin and device owner
786 dpm.setActiveAdmin(admin1, false);
787 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
788
789 // Save password history length
790 dpm.setPasswordHistoryLength(admin1, passwordHistoryLength);
791
792 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
793
794 initializeDpms();
795 reset(mContext.spiedContext);
796
797 // Password history length should persist after rebooted
798 assertEquals(dpm.getPasswordHistoryLength(admin1), passwordHistoryLength);
799 }
800
801 /**
802 * Test for: {@link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000803 *
804 * Validates that when the password for a user changes, the notification broadcast intent
805 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
806 * addition to ones in the original user.
807 */
808 public void testSetActivePasswordState_sendToProfiles() throws Exception {
809 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
810
811 final int MANAGED_PROFILE_USER_ID = 78;
812 final int MANAGED_PROFILE_ADMIN_UID =
813 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
814
815 // Setup device owner.
816 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
817 mContext.packageName = admin1.getPackageName();
818 setupDeviceOwner();
819
820 // Add a managed profile belonging to the system user.
821 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
822
823 // Change the parent user's password.
824 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
825
826 // Both the device owner and the managed profile owner should receive this broadcast.
827 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
828 intent.setComponent(admin1);
829 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
830
831 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
832 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100833 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
834 eq(null),
835 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000836 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
837 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100838 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
839 eq(null),
840 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000841 }
842
843 /**
Rubin Xu19854862019-08-15 16:37:23 +0100844 * Test for: @{link DevicePolicyManager#reportPasswordChanged}
Robin Leed2a73ed2016-12-19 09:07:16 +0000845 *
846 * Validates that when the password for a managed profile changes, the notification broadcast
847 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
848 * its parent.
849 */
850 public void testSetActivePasswordState_notSentToParent() throws Exception {
851 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
852
853 final int MANAGED_PROFILE_USER_ID = 78;
854 final int MANAGED_PROFILE_ADMIN_UID =
855 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
856
857 // Setup device owner.
858 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
859 mContext.packageName = admin1.getPackageName();
Pavel Grafov75c0a892017-05-18 17:28:27 +0100860 doReturn(true).when(getServices().lockPatternUtils)
Robin Leed2a73ed2016-12-19 09:07:16 +0000861 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
862 setupDeviceOwner();
863
864 // Add a managed profile belonging to the system user.
865 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
866
867 // Change the profile's password.
868 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
869
870 // Both the device owner and the managed profile owner should receive this broadcast.
871 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
872 intent.setComponent(admin1);
873 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
874
875 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
876 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100877 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM),
878 eq(null),
879 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000880 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
881 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +0100882 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID),
883 eq(null),
884 any(Bundle.class));
Robin Leed2a73ed2016-12-19 09:07:16 +0000885 }
Lenka Trochtova66c492a2018-12-06 11:29:21 +0100886
Robin Leed2a73ed2016-12-19 09:07:16 +0000887 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000888 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700889 */
890 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000891 setDeviceOwner();
892
893 // Try to set a profile owner on the same user, which should fail.
894 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
895 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
Pavel Grafova1ea8d92017-05-25 21:55:24 +0100896 assertExpectException(IllegalStateException.class,
897 /* messageRegex= */ "already has a device owner",
898 () -> dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM));
Victor Chang3e794af2016-03-04 13:48:17 +0000899
900 // DO admin can't be deactivated.
901 dpm.removeActiveAdmin(admin1);
902 assertTrue(dpm.isAdminActive(admin1));
903
904 // TODO Test getDeviceOwnerName() too. To do so, we need to change
905 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
906 }
907
908 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700909 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800910 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700911 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
912 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
913
Makoto Onukid932f762015-09-29 16:53:38 -0700914 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700915 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
916
Makoto Onukid932f762015-09-29 16:53:38 -0700917 // Make sure admin1 is installed on system user.
918 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700919
Makoto Onukic8a5a552015-11-19 14:29:12 -0800920 // Check various get APIs.
921 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
922
Makoto Onukib643fb02015-09-22 15:03:44 -0700923 // DO needs to be an DA.
924 dpm.setActiveAdmin(admin1, /* replace =*/ false);
925
926 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700927 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700928
Makoto Onukic8a5a552015-11-19 14:29:12 -0800929 // getDeviceOwnerComponent should return the admin1 component.
930 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
931 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
932
933 // Check various get APIs.
934 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
935
936 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
937 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
938 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
939 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
940
941 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
942
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000943 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +0100944 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000945 eq(admin1.getPackageName()));
946
Makoto Onukib643fb02015-09-22 15:03:44 -0700947 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
948 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
949 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
950
Makoto Onukic8a5a552015-11-19 14:29:12 -0800951 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700952 }
953
Makoto Onukic8a5a552015-11-19 14:29:12 -0800954 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
955 final int origCallingUser = mContext.binder.callingUid;
956 final List origPermissions = new ArrayList(mContext.callerPermissions);
957 mContext.callerPermissions.clear();
958
959 mContext.callerPermissions.add(permission.MANAGE_USERS);
960
961 mContext.binder.callingUid = Process.SYSTEM_UID;
962
963 // TODO Test getDeviceOwnerName() too. To do so, we need to change
964 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
965 if (hasDeviceOwner) {
966 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
967 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
968 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
969
970 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
971 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
972 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
973 } else {
974 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
975 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
976 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
977
978 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
979 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
980 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
981 }
982
983 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
984 if (hasDeviceOwner) {
985 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
986 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
987 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
988
989 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
990 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
991 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
992 } else {
993 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
994 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
995 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
996
997 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
998 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
999 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1000 }
1001
1002 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1003 // Still with MANAGE_USERS.
1004 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1005 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1006 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1007
1008 if (hasDeviceOwner) {
1009 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1010 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1011 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1012 } else {
1013 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1014 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1015 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1016 }
1017
1018 mContext.binder.callingUid = Process.SYSTEM_UID;
1019 mContext.callerPermissions.remove(permission.MANAGE_USERS);
1020 // System can still call "OnAnyUser" without MANAGE_USERS.
1021 if (hasDeviceOwner) {
1022 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1023 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1024 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1025
1026 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1027 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
1028 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
1029 } else {
1030 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1031 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1032 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1033
1034 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1035 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
1036 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
1037 }
1038
1039 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1040 // Still no MANAGE_USERS.
1041 if (hasDeviceOwner) {
1042 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1043 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1044 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
1045 } else {
1046 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1047 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1048 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1049 }
1050
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001051 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1052 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1053 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1054 dpm::getDeviceOwnerComponentOnAnyUser);
1055 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1056 dpm::getDeviceOwnerUserId);
1057 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1058 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001059
1060 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1061 // Still no MANAGE_USERS.
1062 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1063 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
1064 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
1065
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001066 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1067 () -> dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
1068 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1069 dpm::getDeviceOwnerComponentOnAnyUser);
1070 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1071 dpm::getDeviceOwnerUserId);
1072 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1073 dpm::getDeviceOwnerNameOnAnyUser);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001074
1075 // Restore.
1076 mContext.binder.callingUid = origCallingUser;
1077 mContext.callerPermissions.addAll(origPermissions);
1078 }
1079
1080
Makoto Onukib643fb02015-09-22 15:03:44 -07001081 /**
1082 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
1083 */
1084 public void testSetDeviceOwner_noSuchPackage() {
1085 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001086 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -07001087 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1088 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1089
1090 // Call from a process on the system user.
1091 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1092
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001093 assertExpectException(IllegalArgumentException.class,
1094 /* messageRegex= */ "Invalid component",
1095 () -> dpm.setDeviceOwner(new ComponentName("a.b.c", ".def")));
Makoto Onukib643fb02015-09-22 15:03:44 -07001096 }
1097
1098 public void testSetDeviceOwner_failures() throws Exception {
1099 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
1100 }
1101
Makoto Onukia52562c2015-10-01 16:12:31 -07001102 public void testClearDeviceOwner() throws Exception {
1103 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001104 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001105 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1106 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1107
1108 // Set admin1 as a DA to the secondary user.
1109 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1110
1111 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1112
1113 // Set admin 1 as the DO to the system user.
1114
1115 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1116 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1117 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1118 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1119
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001120 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001121 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001122 eq(admin1.getPackageName()));
1123
Makoto Onukic8a5a552015-11-19 14:29:12 -08001124 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001125
Makoto Onuki90b89652016-01-28 14:44:18 -08001126 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001127 when(getServices().userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001128 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001129
1130 assertTrue(dpm.isAdminActive(admin1));
1131 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
1132
Makoto Onukia52562c2015-10-01 16:12:31 -07001133 // Set up other mocks.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001134 when(getServices().userManager.getUserRestrictions()).thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001135
1136 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001137 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager).
1138 getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001139
1140 // But first pretend the user is locked. Then it should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001141 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001142 assertExpectException(IllegalStateException.class,
1143 /* messageRegex= */ "User must be running and unlocked",
1144 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001145
Pavel Grafov75c0a892017-05-18 17:28:27 +01001146 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
1147 reset(getServices().userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -07001148 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1149
1150 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001151 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001152
Pavel Grafov75c0a892017-05-18 17:28:27 +01001153 verify(getServices().userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
Victor Chang348f6962017-01-30 16:19:13 +00001154 eq(false),
1155 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
1156
Pavel Grafov75c0a892017-05-18 17:28:27 +01001157 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki90b89652016-01-28 14:44:18 -08001158 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001159 eq(null),
1160 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -08001161
Sudheer Shanka101c3532018-01-08 16:28:42 -08001162 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1163 null, UserHandle.USER_SYSTEM);
1164
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001165 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +01001166
1167 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1168 // and once for clearing it.
1169 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1170 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1171 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001172 // TODO Check other calls.
1173 }
1174
Pavel Grafov775b26d82019-10-30 13:29:01 +00001175 public void testDeviceOwnerBackupActivateDeactivate() throws Exception {
1176 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1177 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1178
1179 // Set admin1 as a DA to the secondary user.
1180 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1181 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1182 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1183 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1184
1185 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1186 eq(UserHandle.USER_SYSTEM), eq(false));
1187
1188 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1189
1190 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1191 eq(UserHandle.USER_SYSTEM), eq(true));
1192 }
1193
1194 public void testProfileOwnerBackupActivateDeactivate() throws Exception {
1195 setAsProfileOwner(admin1);
1196
1197 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1198 eq(DpmMockContext.CALLER_USER_HANDLE), eq(false));
1199
1200 dpm.clearProfileOwner(admin1);
1201
1202 verify(getServices().ibackupManager, times(1)).setBackupServiceActive(
1203 eq(DpmMockContext.CALLER_USER_HANDLE), eq(true));
1204 }
1205
Makoto Onukia52562c2015-10-01 16:12:31 -07001206 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1207 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001208 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001209 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1210 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1211
1212 // Set admin1 as a DA to the secondary user.
1213 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1214
1215 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1216
1217 // Set admin 1 as the DO to the system user.
1218
1219 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1220 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1221 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1222 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1223
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001224 // Verify internal calls.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001225 verify(getServices().iactivityManager, times(1)).updateDeviceOwner(
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001226 eq(admin1.getPackageName()));
1227
Makoto Onukic8a5a552015-11-19 14:29:12 -08001228 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001229
1230 // Now call clear from the secondary user, which should throw.
1231 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1232
1233 // Now call clear.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001234 doReturn(DpmMockContext.CALLER_UID).when(getServices().packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001235 eq(admin1.getPackageName()),
1236 anyInt());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001237 assertExpectException(SecurityException.class,
1238 /* messageRegex =*/ "clearDeviceOwner can only be called by the device owner",
1239 () -> dpm.clearDeviceOwnerApp(admin1.getPackageName()));
Makoto Onukia52562c2015-10-01 16:12:31 -07001240
Makoto Onukic8a5a552015-11-19 14:29:12 -08001241 // DO shouldn't be removed.
1242 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001243 }
1244
Alex Johnston63220932019-09-26 10:10:51 +01001245 /**
1246 * Test for: {@link DevicePolicyManager#clearDeviceOwnerApp(String)}
1247 *
1248 * Validates that when the device owner is removed, the reset password token is cleared
1249 */
1250 public void testClearDeviceOwner_clearResetPasswordToken() throws Exception {
1251 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
1252 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1254
1255 // Install admin1 on system user
1256 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1257
1258 // Set admin1 to active admin and device owner
1259 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1260 dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM);
1261
1262 // Add reset password token
1263 final long handle = 12000;
1264 final byte[] token = new byte[32];
1265 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
1266 nullable(EscrowTokenStateChangeCallback.class)))
1267 .thenReturn(handle);
1268 assertTrue(dpm.setResetPasswordToken(admin1, token));
1269
1270 // Assert reset password token is active
1271 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle),
1272 eq(UserHandle.USER_SYSTEM)))
1273 .thenReturn(true);
1274 assertTrue(dpm.isResetPasswordTokenActive(admin1));
1275
1276 // Remove the device owner
1277 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1278
1279 // Verify password reset password token was removed
1280 verify(getServices().lockPatternUtils).removeEscrowToken(eq(handle),
1281 eq(UserHandle.USER_SYSTEM));
1282 }
1283
Makoto Onukib643fb02015-09-22 15:03:44 -07001284 public void testSetProfileOwner() throws Exception {
1285 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001286
Makoto Onuki90b89652016-01-28 14:44:18 -08001287 // PO admin can't be deactivated.
1288 dpm.removeActiveAdmin(admin1);
1289 assertTrue(dpm.isAdminActive(admin1));
1290
Makoto Onuki803d6752015-10-30 12:58:39 -07001291 // Try setting DO on the same user, which should fail.
1292 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001293 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1294 runAsCaller(mServiceContext, dpms, dpm -> {
1295 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001296 assertExpectException(IllegalStateException.class,
1297 /* messageRegex= */ "already has a profile owner",
1298 () -> dpm.setDeviceOwner(admin2, "owner-name",
1299 DpmMockContext.CALLER_USER_HANDLE));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001300 });
Makoto Onukib643fb02015-09-22 15:03:44 -07001301 }
1302
Makoto Onuki90b89652016-01-28 14:44:18 -08001303 public void testClearProfileOwner() throws Exception {
1304 setAsProfileOwner(admin1);
1305
1306 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1307
1308 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1309 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1310
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001311 // First try when the user is locked, which should fail.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001312 when(getServices().userManager.isUserUnlocked(anyInt()))
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001313 .thenReturn(false);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001314 assertExpectException(IllegalStateException.class,
1315 /* messageRegex= */ "User must be running and unlocked",
1316 () -> dpm.clearProfileOwner(admin1));
1317
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001318 // Clear, really.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001319 when(getServices().userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001320 dpm.clearProfileOwner(admin1);
1321
1322 // Check
1323 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001324 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Sudheer Shanka101c3532018-01-08 16:28:42 -08001325 verify(getServices().usageStatsManagerInternal).setActiveAdminApps(
1326 null, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onuki90b89652016-01-28 14:44:18 -08001327 }
1328
Makoto Onukib643fb02015-09-22 15:03:44 -07001329 public void testSetProfileOwner_failures() throws Exception {
1330 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1331 }
1332
Makoto Onukia52562c2015-10-01 16:12:31 -07001333 public void testGetDeviceOwnerAdminLocked() throws Exception {
1334 checkDeviceOwnerWithMultipleDeviceAdmins();
1335 }
1336
1337 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1338 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1339 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1340 // make sure it gets the right component from the right user.
1341
1342 final int ANOTHER_USER_ID = 100;
1343 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1344
Pavel Grafov75c0a892017-05-18 17:28:27 +01001345 getServices().addUser(ANOTHER_USER_ID, 0); // Add one more user.
Makoto Onukia52562c2015-10-01 16:12:31 -07001346
1347 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001348 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001349 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1350 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1351
1352 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1353
Pavel Grafov75c0a892017-05-18 17:28:27 +01001354 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Change29cd472016-03-02 20:57:42 +00001355
Makoto Onukia52562c2015-10-01 16:12:31 -07001356 // Make sure the admin packge is installed to each user.
1357 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1358 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1359
1360 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1361 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1362
1363 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1364
1365
1366 // Set active admins to the users.
1367 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1368 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1369
1370 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1371 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1372
1373 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1374
1375 // Set DO on the first non-system user.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001376 getServices().setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001377 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1378
Makoto Onukic8a5a552015-11-19 14:29:12 -08001379 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001380
1381 // Then check getDeviceOwnerAdminLocked().
1382 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1383 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1384 }
1385
1386 /**
1387 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001388 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1389 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001390 *
1391 * We didn't use to persist the DO component class name, but now we do, and the above method
1392 * finds the right component from a package name upon migration.
1393 */
1394 public void testDeviceOwnerMigration() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001395 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001396 checkDeviceOwnerWithMultipleDeviceAdmins();
1397
1398 // Overwrite the device owner setting and clears the clas name.
1399 dpms.mOwners.setDeviceOwner(
1400 new ComponentName(admin2.getPackageName(), ""),
1401 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1402 dpms.mOwners.writeDeviceOwner();
1403
1404 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001405 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001406
1407 // Then create a new DPMS to have it load the settings from files.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001408 when(getServices().userManager.getUserRestrictions(any(UserHandle.class)))
Makoto Onuki068c54a2015-10-13 14:34:03 -07001409 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001410 initializeDpms();
1411
1412 // Now the DO component name is a full name.
1413 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1414 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001415 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001416 }
1417
Makoto Onukib643fb02015-09-22 15:03:44 -07001418 public void testSetGetApplicationRestriction() {
1419 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001420 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001421
1422 {
1423 Bundle rest = new Bundle();
1424 rest.putString("KEY_STRING", "Foo1");
1425 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1426 }
1427
1428 {
1429 Bundle rest = new Bundle();
1430 rest.putString("KEY_STRING", "Foo2");
1431 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1432 }
1433
1434 {
1435 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1436 assertNotNull(returned);
1437 assertEquals(returned.size(), 1);
1438 assertEquals(returned.get("KEY_STRING"), "Foo1");
1439 }
1440
1441 {
1442 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1443 assertNotNull(returned);
1444 assertEquals(returned.size(), 1);
1445 assertEquals(returned.get("KEY_STRING"), "Foo2");
1446 }
1447
1448 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1449 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1450 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001451
Edman Anjosf9946772016-11-28 16:35:15 +01001452 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001453 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1454 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001455 *
1456 * @param packageName the name of the package to be setup
1457 * @param appId the application ID to be given to the package
1458 * @return the UID of the package as known by the mock package manager
1459 */
1460 private int setupPackageInPackageManager(final String packageName, final int appId)
1461 throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01001462 return setupPackageInPackageManager(packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001463 ApplicationInfo.FLAG_HAS_CODE);
1464 }
1465
1466 /**
1467 * Setup a package in the package manager mock. Useful for faking installed applications.
1468 *
1469 * @param packageName the name of the package to be setup
1470 * @param userId the user id where the package will be "installed"
1471 * @param appId the application ID to be given to the package
1472 * @param flags flags to set in the ApplicationInfo for this package
1473 * @return the UID of the package as known by the mock package manager
1474 */
Pavel Grafov75c0a892017-05-18 17:28:27 +01001475 private int setupPackageInPackageManager(final String packageName, int userId, final int appId,
1476 int flags) throws Exception {
1477 final int uid = UserHandle.getUid(userId, appId);
1478 // Make the PackageManager return the package instead of throwing NameNotFoundException
Edman Anjosf9946772016-11-28 16:35:15 +01001479 final PackageInfo pi = new PackageInfo();
1480 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001481 pi.applicationInfo.flags = flags;
Pavel Grafov75c0a892017-05-18 17:28:27 +01001482 doReturn(pi).when(getServices().ipackageManager).getPackageInfo(
Edman Anjosf9946772016-11-28 16:35:15 +01001483 eq(packageName),
1484 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001485 eq(userId));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001486 doReturn(pi.applicationInfo).when(getServices().ipackageManager).getApplicationInfo(
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001487 eq(packageName),
1488 anyInt(),
1489 eq(userId));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08001490 doReturn(true).when(getServices().ipackageManager).isPackageAvailable(packageName, userId);
Edman Anjosf9946772016-11-28 16:35:15 +01001491 // Setup application UID with the PackageManager
Pavel Grafov75c0a892017-05-18 17:28:27 +01001492 doReturn(uid).when(getServices().packageManager).getPackageUidAsUser(
Edman Anjosf9946772016-11-28 16:35:15 +01001493 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001494 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001495 // Associate packageName to uid
Pavel Grafov75c0a892017-05-18 17:28:27 +01001496 doReturn(packageName).when(getServices().ipackageManager).getNameForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001497 doReturn(new String[]{packageName})
Pavel Grafov75c0a892017-05-18 17:28:27 +01001498 .when(getServices().ipackageManager).getPackagesForUid(eq(uid));
Edman Anjosf9946772016-11-28 16:35:15 +01001499 return uid;
1500 }
1501
Robin Lee7f5c91c2017-02-08 21:27:02 +00001502 public void testCertificateDisclosure() throws Exception {
1503 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1504 final UserHandle user = UserHandle.of(userId);
1505
1506 mContext.applicationInfo = new ApplicationInfo();
1507 mContext.callerPermissions.add(permission.MANAGE_USERS);
1508 mContext.packageName = "com.android.frameworks.servicestests";
Pavel Grafov75c0a892017-05-18 17:28:27 +01001509 getServices().addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001510 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1511
Robin Leeabaa0692017-02-20 20:54:22 +00001512 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1513 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001514
1515 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1516 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1517
1518 // Given that we have exactly one certificate installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001519 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001520 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001521 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001522 // a notification should not be shown.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001523 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001524 .cancelAsUser(anyString(), anyInt(), eq(user));
1525
1526 // Given that we have four certificates installed,
Pavel Grafov75c0a892017-05-18 17:28:27 +01001527 when(getServices().keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001528 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001529 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1530 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001531 // a notification should be shown saying that there are two certificates left to approve.
Pavel Grafov75c0a892017-05-18 17:28:27 +01001532 verify(getServices().notificationManager, timeout(1000))
Robin Lee7f5c91c2017-02-08 21:27:02 +00001533 .notifyAsUser(anyString(), anyInt(), argThat(
1534 new BaseMatcher<Notification>() {
1535 @Override
1536 public boolean matches(Object item) {
1537 final Notification noti = (Notification) item;
1538 return TEST_STRING.equals(
1539 noti.extras.getString(Notification.EXTRA_TITLE));
1540 }
1541 @Override
1542 public void describeTo(Description description) {
1543 description.appendText(
1544 "Notification{title=\"" + TEST_STRING + "\"}");
1545 }
1546 }), eq(user));
1547 }
1548
Edman Anjosf9946772016-11-28 16:35:15 +01001549 /**
1550 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1551 * privileges can acually be exercised by a delegate are not covered here.
1552 */
1553 public void testDelegation() throws Exception {
1554 setAsProfileOwner(admin1);
1555
1556 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1557
1558 // Given two packages
1559 final String CERT_DELEGATE = "com.delegate.certs";
1560 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1561 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1562 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1563 20989);
1564
1565 // On delegation
1566 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1567 mContext.packageName = admin1.getPackageName();
1568 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1569 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1570
1571 // DPMS correctly stores and retrieves the delegates
1572 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1573 assertEquals(2, policy.mDelegationMap.size());
1574 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1575 DELEGATION_CERT_INSTALL);
1576 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1577 DELEGATION_CERT_INSTALL);
1578 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1579 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1580 DELEGATION_APP_RESTRICTIONS);
1581 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1582 DELEGATION_APP_RESTRICTIONS);
1583 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1584
1585 // On calling install certificate APIs from an unauthorized process
1586 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1587 mContext.packageName = RESTRICTIONS_DELEGATE;
1588
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001589 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1590 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001591
1592 // On calling install certificate APIs from an authorized process
1593 mContext.binder.callingUid = CERT_DELEGATE_UID;
1594 mContext.packageName = CERT_DELEGATE;
1595
1596 // DPMS executes without a SecurityException
1597 try {
1598 dpm.installCaCert(null, null);
1599 } catch (SecurityException unexpected) {
1600 fail("Threw SecurityException on authorized access");
1601 } catch (NullPointerException expected) {
1602 }
1603
1604 // On removing a delegate
1605 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1606 mContext.packageName = admin1.getPackageName();
1607 dpm.setCertInstallerPackage(admin1, null);
1608
1609 // DPMS does not allow access to ex-delegate
1610 mContext.binder.callingUid = CERT_DELEGATE_UID;
1611 mContext.packageName = CERT_DELEGATE;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001612 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
1613 () -> dpm.installCaCert(null, null));
Edman Anjosf9946772016-11-28 16:35:15 +01001614
1615 // But still allows access to other existing delegates
1616 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1617 mContext.packageName = RESTRICTIONS_DELEGATE;
1618 try {
1619 dpm.getApplicationRestrictions(null, "pkg");
1620 } catch (SecurityException expected) {
1621 fail("Threw SecurityException on authorized access");
1622 }
1623 }
1624
Esteban Talaverabf60f722015-12-10 16:26:44 +00001625 public void testApplicationRestrictionsManagingApp() throws Exception {
1626 setAsProfileOwner(admin1);
1627
Rubin Xued1928a2016-02-11 17:23:06 +00001628 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001629 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001630 final String nonDelegateExceptionMessageRegex =
1631 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001632 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001633 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1634 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001635
Esteban Talaverabf60f722015-12-10 16:26:44 +00001636 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1637 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001638 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1639 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001640 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001641 final Bundle rest = new Bundle();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001642 rest.putString("KEY_STRING", "Foo1");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001643 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1644 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001645
1646 // Check via the profile owner that no restrictions were set.
1647 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001648 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001649 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1650
Rubin Xued1928a2016-02-11 17:23:06 +00001651 // Check the API does not allow setting a non-existent package
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001652 assertExpectException(PackageManager.NameNotFoundException.class,
1653 /* messageRegex= */ nonExistAppRestrictionsManagerPackage,
1654 () -> dpm.setApplicationRestrictionsManagingPackage(
1655 admin1, nonExistAppRestrictionsManagerPackage));
Rubin Xued1928a2016-02-11 17:23:06 +00001656
Esteban Talaverabf60f722015-12-10 16:26:44 +00001657 // Let appRestrictionsManagerPackage manage app restrictions
1658 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1659 assertEquals(appRestrictionsManagerPackage,
1660 dpm.getApplicationRestrictionsManagingPackage(admin1));
1661
1662 // Now that package should be able to set and retrieve app restrictions.
1663 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001664 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001665 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1666 dpm.setApplicationRestrictions(null, "pkg1", rest);
1667 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1668 assertEquals(1, returned.size(), 1);
1669 assertEquals("Foo1", returned.get("KEY_STRING"));
1670
1671 // The same app running on a separate user shouldn't be able to manage app restrictions.
1672 mContext.binder.callingUid = UserHandle.getUid(
1673 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1674 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001675 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1676 () -> dpm.setApplicationRestrictions(null, "pkg1", rest));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001677
1678 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1679 // too.
1680 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001681 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001682 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1683 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1684 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1685
1686 // Removing the ability for the package to manage app restrictions.
1687 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1688 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1689 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001690 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001691 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001692 assertExpectException(SecurityException.class, nonDelegateExceptionMessageRegex,
1693 () -> dpm.setApplicationRestrictions(null, "pkg1", null));
Esteban Talaverabf60f722015-12-10 16:26:44 +00001694 }
1695
Makoto Onukia4f11972015-10-01 13:19:58 -07001696 public void testSetUserRestriction_asDo() throws Exception {
1697 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001698 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001699 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1700 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1701
1702 // First, set DO.
1703
1704 // Call from a process on the system user.
1705 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1706
1707 // Make sure admin1 is installed on system user.
1708 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001709
1710 // Call.
1711 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001712 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001713 UserHandle.USER_SYSTEM));
1714
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001715 // Check that the user restrictions that are enabled by default are set. Then unset them.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01001716 final String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001717 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001718 DpmTestUtils.assertRestrictions(
1719 DpmTestUtils.newRestrictions(defaultRestrictions),
1720 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1721 );
1722 DpmTestUtils.assertRestrictions(
1723 DpmTestUtils.newRestrictions(defaultRestrictions),
1724 dpm.getUserRestrictions(admin1)
1725 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001726 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001727 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001728 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001729 eq(true) /* isDeviceOwner */,
1730 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001731 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001732 reset(getServices().userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001733
1734 for (String restriction : defaultRestrictions) {
1735 dpm.clearUserRestriction(admin1, restriction);
1736 }
1737
Esteban Talavera548a04b2016-12-20 15:22:30 +00001738 assertNoDeviceOwnerRestrictions();
Pavel Grafov75c0a892017-05-18 17:28:27 +01001739 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001740
1741 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001742 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001743 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001744 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1745 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001746 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001747
Makoto Onukia4f11972015-10-01 13:19:58 -07001748 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001749 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001750 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001751 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1752 UserManager.DISALLOW_ADD_USER),
1753 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001754 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001755
Makoto Onuki068c54a2015-10-13 14:34:03 -07001756 DpmTestUtils.assertRestrictions(
1757 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001758 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001759 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1760 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001761 DpmTestUtils.assertRestrictions(
1762 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001763 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001764 dpm.getUserRestrictions(admin1)
1765 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001766
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001767 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001768 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001769 eq(UserHandle.USER_SYSTEM),
1770 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001771 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001772 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001773
Makoto Onuki068c54a2015-10-13 14:34:03 -07001774 DpmTestUtils.assertRestrictions(
1775 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1776 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1777 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001778 DpmTestUtils.assertRestrictions(
1779 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1780 dpm.getUserRestrictions(admin1)
1781 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001782
1783 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001784 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001785 eq(UserHandle.USER_SYSTEM),
1786 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001787 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001788 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001789
Esteban Talavera548a04b2016-12-20 15:22:30 +00001790 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001791
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001792 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1793 // DO sets them, the scope is global.
1794 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001795 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001796 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001797 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001798 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001799 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001800 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1801 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001802 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001803
1804 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1805 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001806 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001807
1808 // More tests.
1809 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001810 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001811 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001812 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1813 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001814 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001815
1816 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001817 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001818 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001819 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001820 UserManager.DISALLOW_ADD_USER),
1821 eq(true), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001822 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001823
1824 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001825 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001826 eq(UserHandle.USER_SYSTEM),
1827 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001828 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001829 UserManager.DISALLOW_ADD_USER),
1830 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001831 reset(getServices().userManagerInternal);
Eric Sandnessca5969d2018-08-10 13:28:46 +01001832 }
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001833
Eric Sandnessca5969d2018-08-10 13:28:46 +01001834 public void testDaDisallowedPolicies_SecurityException() throws Exception {
1835 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1836 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001837
Eric Sandnessca5969d2018-08-10 13:28:46 +01001838 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1839 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001840
Eric Sandnessca5969d2018-08-10 13:28:46 +01001841 boolean originalCameraDisabled = dpm.getCameraDisabled(admin1);
1842 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1843 () -> dpm.setCameraDisabled(admin1, true));
1844 assertEquals(originalCameraDisabled, dpm.getCameraDisabled(admin1));
1845
1846 int originalKeyguardDisabledFeatures = dpm.getKeyguardDisabledFeatures(admin1);
1847 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1848 () -> dpm.setKeyguardDisabledFeatures(admin1,
1849 DevicePolicyManager.KEYGUARD_DISABLE_FEATURES_ALL));
1850 assertEquals(originalKeyguardDisabledFeatures, dpm.getKeyguardDisabledFeatures(admin1));
1851
1852 long originalPasswordExpirationTimeout = dpm.getPasswordExpirationTimeout(admin1);
1853 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1854 () -> dpm.setPasswordExpirationTimeout(admin1, 1234));
1855 assertEquals(originalPasswordExpirationTimeout, dpm.getPasswordExpirationTimeout(admin1));
1856
1857 int originalPasswordQuality = dpm.getPasswordQuality(admin1);
1858 assertExpectException(SecurityException.class, /* messageRegex= */ null,
1859 () -> dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_NUMERIC));
1860 assertEquals(originalPasswordQuality, dpm.getPasswordQuality(admin1));
Makoto Onukia4f11972015-10-01 13:19:58 -07001861 }
1862
1863 public void testSetUserRestriction_asPo() {
1864 setAsProfileOwner(admin1);
1865
Makoto Onuki068c54a2015-10-13 14:34:03 -07001866 DpmTestUtils.assertRestrictions(
1867 DpmTestUtils.newRestrictions(),
1868 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1869 .ensureUserRestrictions()
1870 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001871
1872 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001873 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001874 eq(DpmMockContext.CALLER_USER_HANDLE),
1875 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001876 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001877 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001878
Makoto Onukia4f11972015-10-01 13:19:58 -07001879 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001880 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001881 eq(DpmMockContext.CALLER_USER_HANDLE),
1882 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1883 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001884 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001885 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001886
Makoto Onuki068c54a2015-10-13 14:34:03 -07001887 DpmTestUtils.assertRestrictions(
1888 DpmTestUtils.newRestrictions(
1889 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1890 UserManager.DISALLOW_OUTGOING_CALLS
1891 ),
1892 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1893 .ensureUserRestrictions()
1894 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001895 DpmTestUtils.assertRestrictions(
1896 DpmTestUtils.newRestrictions(
1897 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1898 UserManager.DISALLOW_OUTGOING_CALLS
1899 ),
1900 dpm.getUserRestrictions(admin1)
1901 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001902
1903 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001904 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001905 eq(DpmMockContext.CALLER_USER_HANDLE),
1906 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001907 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001908 reset(getServices().userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001909
1910 DpmTestUtils.assertRestrictions(
1911 DpmTestUtils.newRestrictions(
1912 UserManager.DISALLOW_OUTGOING_CALLS
1913 ),
1914 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1915 .ensureUserRestrictions()
1916 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001917 DpmTestUtils.assertRestrictions(
1918 DpmTestUtils.newRestrictions(
1919 UserManager.DISALLOW_OUTGOING_CALLS
1920 ),
1921 dpm.getUserRestrictions(admin1)
1922 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001923
1924 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001925 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001926 eq(DpmMockContext.CALLER_USER_HANDLE),
1927 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001928 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001929 reset(getServices().userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001930
Makoto Onuki068c54a2015-10-13 14:34:03 -07001931 DpmTestUtils.assertRestrictions(
1932 DpmTestUtils.newRestrictions(),
1933 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1934 .ensureUserRestrictions()
1935 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001936 DpmTestUtils.assertRestrictions(
1937 DpmTestUtils.newRestrictions(),
1938 dpm.getUserRestrictions(admin1)
1939 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001940
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001941 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1942 // though when DO sets them they'll be applied globally.
1943 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001944 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001945 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001946 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001947 eq(DpmMockContext.CALLER_USER_HANDLE),
1948 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1949 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001950 eq(false), eq(CAMERA_NOT_DISABLED));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001951 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001952
1953 dpm.setCameraDisabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01001954 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001955 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001956 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001957 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001958 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Pavel Grafov75c0a892017-05-18 17:28:27 +01001959 reset(getServices().userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001960
Makoto Onukia4f11972015-10-01 13:19:58 -07001961 // TODO Make sure restrictions are written to the file.
1962 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001963
Esteban Talavera548a04b2016-12-20 15:22:30 +00001964
1965 public void testDefaultEnabledUserRestrictions() throws Exception {
1966 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1967 mContext.callerPermissions.add(permission.MANAGE_USERS);
1968 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1969 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1970
1971 // First, set DO.
1972
1973 // Call from a process on the system user.
1974 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1975
1976 // Make sure admin1 is installed on system user.
1977 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1978
1979 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1980 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1981 UserHandle.USER_SYSTEM));
1982
1983 // Check that the user restrictions that are enabled by default are set. Then unset them.
1984 String[] defaultRestrictions = UserRestrictionsUtils
1985 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1986 assertTrue(defaultRestrictions.length > 0);
1987 DpmTestUtils.assertRestrictions(
1988 DpmTestUtils.newRestrictions(defaultRestrictions),
1989 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1990 );
1991 DpmTestUtils.assertRestrictions(
1992 DpmTestUtils.newRestrictions(defaultRestrictions),
1993 dpm.getUserRestrictions(admin1)
1994 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01001995 verify(getServices().userManagerInternal).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00001996 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001997 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001998 eq(true) /* isDeviceOwner */,
1999 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002000 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002001 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002002
2003 for (String restriction : defaultRestrictions) {
2004 dpm.clearUserRestriction(admin1, restriction);
2005 }
2006
2007 assertNoDeviceOwnerRestrictions();
2008
2009 // Initialize DPMS again and check that the user restriction wasn't enabled again.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002010 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002011 initializeDpms();
2012 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2013 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2014
2015 assertNoDeviceOwnerRestrictions();
2016
2017 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
2018 // is set as it wasn't enabled during setDeviceOwner.
2019 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
2020 assertFalse(UserRestrictionsUtils
2021 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
2022 UserRestrictionsUtils
2023 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
2024 try {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002025 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002026 initializeDpms();
2027 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2028 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2029
2030 DpmTestUtils.assertRestrictions(
2031 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2032 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2033 );
2034 DpmTestUtils.assertRestrictions(
2035 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
2036 dpm.getUserRestrictions(admin1)
2037 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002038 verify(getServices().userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
Esteban Talavera548a04b2016-12-20 15:22:30 +00002039 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00002040 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01002041 eq(true) /* isDeviceOwner */,
2042 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00002043 );
Pavel Grafov75c0a892017-05-18 17:28:27 +01002044 reset(getServices().userManagerInternal);
Esteban Talavera548a04b2016-12-20 15:22:30 +00002045
2046 // Remove the restriction.
2047 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
2048
2049 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
2050 initializeDpms();
2051 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
2052 assertNotNull(dpms.getDeviceOwnerAdminLocked());
2053 assertNoDeviceOwnerRestrictions();
2054 } finally {
2055 UserRestrictionsUtils
2056 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
2057 }
2058 }
2059
2060 private void assertNoDeviceOwnerRestrictions() {
2061 DpmTestUtils.assertRestrictions(
2062 DpmTestUtils.newRestrictions(),
2063 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
2064 );
2065 DpmTestUtils.assertRestrictions(
2066 DpmTestUtils.newRestrictions(),
2067 dpm.getUserRestrictions(admin1)
2068 );
2069 }
2070
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002071 public void testGetMacAddress() throws Exception {
2072 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2073 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2074 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2075
2076 // In this test, change the caller user to "system".
2077 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2078
2079 // Make sure admin1 is installed on system user.
2080 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2081
2082 // Test 1. Caller doesn't have DO or DA.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002083 assertExpectException(SecurityException.class, /* messageRegex= */ "No active admin",
2084 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002085
2086 // DO needs to be an DA.
2087 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2088 assertTrue(dpm.isAdminActive(admin1));
2089
2090 // Test 2. Caller has DA, but not DO.
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002091 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2092 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002093
2094 // Test 3. Caller has PO, but not DO.
2095 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002096 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2097 () -> dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002098
2099 // Remove PO.
2100 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002101 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002102 // Test 4, Caller is DO now.
2103 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2104
xshu425b9a62018-12-13 14:18:18 -08002105 // 4-1. But WifiManager is not ready.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002106 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002107
xshu425b9a62018-12-13 14:18:18 -08002108 // 4-2. When WifiManager returns an empty array, dpm should also output null.
2109 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(new String[0]);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002110 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002111
2112 // 4-3. With a real MAC address.
xshu425b9a62018-12-13 14:18:18 -08002113 final String[] macAddresses = new String[]{"11:22:33:44:55:66"};
2114 when(getServices().wifiManager.getFactoryMacAddresses()).thenReturn(macAddresses);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08002115 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08002116 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002117
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002118 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002119 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2120 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2121
2122 // In this test, change the caller user to "system".
2123 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2124
2125 // Make sure admin1 is installed on system user.
2126 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2127
2128 // Set admin1 as DA.
2129 dpm.setActiveAdmin(admin1, false);
2130 assertTrue(dpm.isAdminActive(admin1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002131 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2132 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002133
2134 // Set admin1 as PO.
2135 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002136 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_DEVICE_OWNER_MSG,
2137 () -> dpm.reboot(admin1));
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002138
2139 // Remove PO and add DO.
2140 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07002141 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002142 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2143
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002144 // admin1 is DO.
2145 // Set current call state of device to ringing.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002146 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002147 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002148 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2149 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002150
2151 // Set current call state of device to dialing/active.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002152 when(getServices().telephonyManager.getCallState())
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002153 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002154 assertExpectException(IllegalStateException.class, /* messageRegex= */ ONGOING_CALL_MSG,
2155 () -> dpm.reboot(admin1));
Mahaver Chopra1216ae52016-03-11 15:39:48 +00002156
2157 // Set current call state of device to idle.
Pavel Grafov75c0a892017-05-18 17:28:27 +01002158 when(getServices().telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00002159 dpm.reboot(admin1);
2160 }
Kenny Guy06de4e72015-12-22 12:07:39 +00002161
2162 public void testSetGetSupportText() {
2163 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2164 dpm.setActiveAdmin(admin1, true);
2165 dpm.setActiveAdmin(admin2, true);
2166 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2167
2168 // Null default support messages.
2169 {
2170 assertNull(dpm.getLongSupportMessage(admin1));
2171 assertNull(dpm.getShortSupportMessage(admin1));
2172 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2173 assertNull(dpm.getShortSupportMessageForUser(admin1,
2174 DpmMockContext.CALLER_USER_HANDLE));
2175 assertNull(dpm.getLongSupportMessageForUser(admin1,
2176 DpmMockContext.CALLER_USER_HANDLE));
2177 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2178 }
2179
2180 // Only system can call the per user versions.
2181 {
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002182 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2183 () -> dpm.getShortSupportMessageForUser(admin1,
2184 DpmMockContext.CALLER_USER_HANDLE));
2185 assertExpectException(SecurityException.class, /* messageRegex= */ "message for user",
2186 () -> dpm.getLongSupportMessageForUser(admin1,
2187 DpmMockContext.CALLER_USER_HANDLE));
Kenny Guy06de4e72015-12-22 12:07:39 +00002188 }
2189
2190 // Can't set message for admin in another uid.
2191 {
2192 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002193 assertExpectException(SecurityException.class,
2194 /* messageRegex= */ "is not owned by uid",
2195 () -> dpm.setShortSupportMessage(admin1, "Some text"));
Kenny Guy06de4e72015-12-22 12:07:39 +00002196 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2197 }
2198
2199 // Set/Get short returns what it sets and other admins text isn't changed.
2200 {
2201 final String supportText = "Some text to test with.";
2202 dpm.setShortSupportMessage(admin1, supportText);
2203 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2204 assertNull(dpm.getLongSupportMessage(admin1));
2205 assertNull(dpm.getShortSupportMessage(admin2));
2206
2207 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2208 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2209 DpmMockContext.CALLER_USER_HANDLE));
2210 assertNull(dpm.getShortSupportMessageForUser(admin2,
2211 DpmMockContext.CALLER_USER_HANDLE));
2212 assertNull(dpm.getLongSupportMessageForUser(admin1,
2213 DpmMockContext.CALLER_USER_HANDLE));
2214 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2215
2216 dpm.setShortSupportMessage(admin1, null);
2217 assertNull(dpm.getShortSupportMessage(admin1));
2218 }
2219
2220 // Set/Get long returns what it sets and other admins text isn't changed.
2221 {
2222 final String supportText = "Some text to test with.\nWith more text.";
2223 dpm.setLongSupportMessage(admin1, supportText);
2224 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2225 assertNull(dpm.getShortSupportMessage(admin1));
2226 assertNull(dpm.getLongSupportMessage(admin2));
2227
2228 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2229 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2230 DpmMockContext.CALLER_USER_HANDLE));
2231 assertNull(dpm.getLongSupportMessageForUser(admin2,
2232 DpmMockContext.CALLER_USER_HANDLE));
2233 assertNull(dpm.getShortSupportMessageForUser(admin1,
2234 DpmMockContext.CALLER_USER_HANDLE));
2235 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2236
2237 dpm.setLongSupportMessage(admin1, null);
2238 assertNull(dpm.getLongSupportMessage(admin1));
2239 }
2240 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002241
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002242 public void testSetGetMeteredDataDisabledPackages() throws Exception {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002243 setAsProfileOwner(admin1);
2244
2245 final ArrayList<String> emptyList = new ArrayList<>();
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002246 assertEquals(emptyList, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002247
2248 // Setup
2249 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2250 final String package1 = "com.example.one";
2251 final String package2 = "com.example.two";
2252 pkgsToRestrict.add(package1);
2253 pkgsToRestrict.add(package2);
2254 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2255 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002256 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002257
2258 // Verify
2259 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002260 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002261 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2262 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2263 eq(DpmMockContext.CALLER_USER_HANDLE));
2264
2265 // Setup
2266 pkgsToRestrict.remove(package1);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002267 excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002268
2269 // Verify
2270 assertEquals(emptyList, excludedPkgs);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002271 assertEquals(pkgsToRestrict, dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002272 verify(getServices().networkPolicyManagerInternal).setMeteredRestrictedPackages(
2273 MockUtils.checkApps(pkgsToRestrict.toArray(new String[0])),
2274 eq(DpmMockContext.CALLER_USER_HANDLE));
2275 }
2276
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002277 public void testSetGetMeteredDataDisabledPackages_deviceAdmin() {
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002278 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2279 dpm.setActiveAdmin(admin1, true);
2280 assertTrue(dpm.isAdminActive(admin1));
2281 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
2282
2283 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002284 () -> dpm.setMeteredDataDisabledPackages(admin1, new ArrayList<>()));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002285 assertExpectException(SecurityException.class, /* messageRegex= */ NOT_PROFILE_OWNER_MSG,
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002286 () -> dpm.getMeteredDataDisabledPackages(admin1));
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08002287 }
2288
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002289 public void testIsMeteredDataDisabledForUserPackage() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002290 setAsProfileOwner(admin1);
2291
2292 // Setup
2293 final ArrayList<String> emptyList = new ArrayList<>();
2294 final ArrayList<String> pkgsToRestrict = new ArrayList<>();
2295 final String package1 = "com.example.one";
2296 final String package2 = "com.example.two";
2297 final String package3 = "com.example.three";
2298 pkgsToRestrict.add(package1);
2299 pkgsToRestrict.add(package2);
2300 setupPackageInPackageManager(package1, DpmMockContext.CALLER_USER_HANDLE, 123, 0);
2301 setupPackageInPackageManager(package2, DpmMockContext.CALLER_USER_HANDLE, 456, 0);
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002302 List<String> excludedPkgs = dpm.setMeteredDataDisabledPackages(admin1, pkgsToRestrict);
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002303
2304 // Verify
2305 assertEquals(emptyList, excludedPkgs);
2306 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2307 assertTrue(package1 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002308 dpm.isMeteredDataDisabledPackageForUser(admin1, package1,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002309 DpmMockContext.CALLER_USER_HANDLE));
2310 assertTrue(package2 + "should be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002311 dpm.isMeteredDataDisabledPackageForUser(admin1, package2,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002312 DpmMockContext.CALLER_USER_HANDLE));
2313 assertFalse(package3 + "should not be restricted",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002314 dpm.isMeteredDataDisabledPackageForUser(admin1, package3,
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002315 DpmMockContext.CALLER_USER_HANDLE));
2316 }
2317
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002318 public void testIsMeteredDataDisabledForUserPackage_nonSystemUidCaller() throws Exception {
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002319 setAsProfileOwner(admin1);
2320 assertExpectException(SecurityException.class,
2321 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002322 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002323 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2324 dpm.clearProfileOwner(admin1);
2325
2326 setDeviceOwner();
2327 assertExpectException(SecurityException.class,
2328 /* messageRegex= */ "Only the system can query restricted pkgs",
Michael Wachenschwanz54164682018-03-08 16:23:52 -08002329 () -> dpm.isMeteredDataDisabledPackageForUser(
Sudheer Shanka5be44ff2018-01-23 15:15:03 -08002330 admin1, "com.example.one", DpmMockContext.CALLER_USER_HANDLE));
2331 clearDeviceOwner();
2332 }
2333
phweiss73145f42017-01-17 19:06:38 +01002334 public void testCreateAdminSupportIntent() throws Exception {
2335 // Setup device owner.
2336 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2337 setupDeviceOwner();
2338
2339 // Nonexisting permission returns null
2340 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2341 assertNull(intent);
2342
2343 // Existing permission that is not set returns null
2344 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2345 assertNull(intent);
2346
2347 // Existing permission that is not set by device/profile owner returns null
Pavel Grafov75c0a892017-05-18 17:28:27 +01002348 when(getServices().userManager.hasUserRestriction(
phweiss73145f42017-01-17 19:06:38 +01002349 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2350 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2351 .thenReturn(true);
2352 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2353 assertNull(intent);
2354
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002355 // UM.getUserRestrictionSources() will return a list of size 1 with the caller resource.
2356 doAnswer((Answer<List<UserManager.EnforcingUser>>) invocation -> Collections.singletonList(
2357 new UserManager.EnforcingUser(
2358 UserHandle.myUserId(), UserManager.RESTRICTION_SOURCE_DEVICE_OWNER))
2359 ).when(getServices().userManager).getUserRestrictionSources(
phweiss73145f42017-01-17 19:06:38 +01002360 eq(UserManager.DISALLOW_ADJUST_VOLUME),
Irina Dumitrescuedc3e6a2019-03-14 17:00:14 +00002361 eq(UserHandle.getUserHandleForUid(UserHandle.myUserId())));
phweiss73145f42017-01-17 19:06:38 +01002362 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2363 assertNotNull(intent);
2364 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2365 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2366 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002367 assertEquals(admin1, intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
phweiss73145f42017-01-17 19:06:38 +01002368 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2369 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2370
Lenka Trochtova3b6e0872018-08-09 14:16:45 +02002371 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2372 // user restrictions
phweiss73145f42017-01-17 19:06:38 +01002373
2374 // Camera is not disabled
2375 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2376 assertNull(intent);
2377
2378 // Camera is disabled
2379 dpm.setCameraDisabled(admin1, true);
2380 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2381 assertNotNull(intent);
2382 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2383 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2384
2385 // Screen capture is not disabled
2386 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2387 assertNull(intent);
2388
2389 // Screen capture is disabled
2390 dpm.setScreenCaptureDisabled(admin1, true);
2391 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2392 assertNotNull(intent);
2393 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2394 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2395
2396 // Same checks for different user
2397 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2398 // Camera should be disabled by device owner
2399 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2400 assertNotNull(intent);
2401 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2402 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2403 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2404 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2405 // ScreenCapture should not be disabled by device owner
2406 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2407 assertNull(intent);
2408 }
2409
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002410 /**
2411 * Test for:
2412 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002413 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002414 * {@link DevicePolicyManager#isAffiliatedUser}
2415 */
2416 public void testUserAffiliation() throws Exception {
2417 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2418 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2419 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2420
2421 // Check that the system user is unaffiliated.
2422 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2423 assertFalse(dpm.isAffiliatedUser());
2424
2425 // Set a device owner on the system user. Check that the system user becomes affiliated.
2426 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2427 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2428 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2429 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002430 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002431
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002432 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002433 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2434 setAsProfileOwner(admin2);
2435 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002436 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002437
2438 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2439 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002440 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002441 userAffiliationIds.add("red");
2442 userAffiliationIds.add("green");
2443 userAffiliationIds.add("blue");
2444 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002445 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002446 assertFalse(dpm.isAffiliatedUser());
2447
2448 // Have the device owner specify a set of affiliation ids that do not intersect with those
2449 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002450 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002451 deviceAffiliationIds.add("cyan");
2452 deviceAffiliationIds.add("yellow");
2453 deviceAffiliationIds.add("magenta");
2454 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2455 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002456 MoreAsserts.assertContentsInAnyOrder(
2457 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002458 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2459 assertFalse(dpm.isAffiliatedUser());
2460
2461 // Have the profile owner specify a set of affiliation ids that intersect with those
2462 // specified by the device owner. Check that the test user becomes affiliated.
2463 userAffiliationIds.add("yellow");
2464 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002465 MoreAsserts.assertContentsInAnyOrder(
2466 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002467 assertTrue(dpm.isAffiliatedUser());
2468
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002469 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002470 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002471 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002472 assertFalse(dpm.isAffiliatedUser());
2473
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002474 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2475 dpm.setAffiliationIds(admin2, userAffiliationIds);
2476 assertTrue(dpm.isAffiliatedUser());
2477 dpm.clearProfileOwner(admin2);
2478 assertFalse(dpm.isAffiliatedUser());
2479
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002480 // Check that the system user remains affiliated.
2481 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2482 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002483
2484 // Clear the device owner - the user becomes unaffiliated.
2485 clearDeviceOwner();
2486 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002487 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002488
2489 public void testGetUserProvisioningState_defaultResult() {
Eric Sandness3780c092018-03-23 16:16:11 +00002490 mContext.callerPermissions.add(permission.MANAGE_USERS);
Alan Treadwayafad8782016-01-19 15:15:08 +00002491 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2492 }
2493
2494 public void testSetUserProvisioningState_permission() 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_unprivileged() throws Exception {
2502 setupProfileOwner();
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002503 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
2504 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2505 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002506 }
2507
2508 public void testSetUserProvisioningState_noManagement() {
2509 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Eric Sandness3780c092018-03-23 16:16:11 +00002510 mContext.callerPermissions.add(permission.MANAGE_USERS);
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002511 assertExpectException(IllegalStateException.class,
2512 /* messageRegex= */ "change provisioning state unless a .* owner is set",
2513 () -> dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2514 DpmMockContext.CALLER_USER_HANDLE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002515 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2516 }
2517
2518 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2519 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2520 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002521
2522 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2523 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2524 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2525 }
2526
2527 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2528 throws Exception {
2529 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2530 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002531
2532 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2533 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2534 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2535 }
2536
2537 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2539 setupDeviceOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002540
2541 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2542 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2543 }
2544
2545 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2546 throws Exception {
2547 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002548
2549 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2550 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2551 DevicePolicyManager.STATE_USER_UNMANAGED);
2552 }
2553
2554 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2555 throws Exception {
2556 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002557
2558 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2559 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2560 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2561 }
2562
2563 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2564 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002565
2566 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2567 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2568 }
2569
2570 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2571 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002572
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002573 assertExpectException(IllegalStateException.class,
2574 /* messageRegex= */ "Cannot move to user provisioning state",
2575 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2576 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2577 DevicePolicyManager.STATE_USER_UNMANAGED));
Alan Treadwayafad8782016-01-19 15:15:08 +00002578 }
2579
2580 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2581 throws Exception {
2582 setupProfileOwner();
Alan Treadwayafad8782016-01-19 15:15:08 +00002583
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002584 assertExpectException(IllegalStateException.class,
2585 /* messageRegex= */ "Cannot move to user provisioning state",
2586 () -> exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2587 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2588 DevicePolicyManager.STATE_USER_SETUP_COMPLETE));
Alan Treadwayafad8782016-01-19 15:15:08 +00002589 }
2590
2591 private void exerciseUserProvisioningTransitions(int userId, int... states) {
Eric Sandness3780c092018-03-23 16:16:11 +00002592 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2593 mContext.callerPermissions.add(permission.MANAGE_USERS);
2594
Alan Treadwayafad8782016-01-19 15:15:08 +00002595 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2596 for (int state : states) {
2597 dpm.setUserProvisioningState(state, userId);
2598 assertEquals(state, dpm.getUserProvisioningState());
2599 }
2600 }
2601
2602 private void setupProfileOwner() throws Exception {
2603 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2604
2605 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2606 dpm.setActiveAdmin(admin1, false);
2607 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2608
2609 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2610 }
2611
2612 private void setupDeviceOwner() throws Exception {
2613 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2614
2615 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2616 dpm.setActiveAdmin(admin1, false);
2617 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2618
2619 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2620 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002621
2622 public void testSetMaximumTimeToLock() {
2623 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2624
2625 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2626 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2627
Pavel Grafov75c0a892017-05-18 17:28:27 +01002628 reset(getServices().powerManagerInternal);
2629 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002630
2631 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002632 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2633 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002634 reset(getServices().powerManagerInternal);
2635 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002636
2637 dpm.setMaximumTimeToLock(admin1, 1);
Pavel Grafov28939982017-10-03 15:11:52 +01002638 verifyScreenTimeoutCall(1L, UserHandle.USER_SYSTEM);
2639 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002640 reset(getServices().powerManagerInternal);
2641 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002642
2643 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002644 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2645 verifyStayOnWhilePluggedCleared(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002646 reset(getServices().powerManagerInternal);
2647 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002648
2649 dpm.setMaximumTimeToLock(admin1, 5);
Pavel Grafov28939982017-10-03 15:11:52 +01002650 verifyScreenTimeoutCall(5L, UserHandle.USER_SYSTEM);
2651 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002652 reset(getServices().powerManagerInternal);
2653 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002654
2655 dpm.setMaximumTimeToLock(admin2, 4);
Pavel Grafov28939982017-10-03 15:11:52 +01002656 verifyScreenTimeoutCall(4L, UserHandle.USER_SYSTEM);
2657 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002658 reset(getServices().powerManagerInternal);
2659 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002660
2661 dpm.setMaximumTimeToLock(admin1, 0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002662 reset(getServices().powerManagerInternal);
2663 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002664
Pavel Grafov28939982017-10-03 15:11:52 +01002665 dpm.setMaximumTimeToLock(admin2, Long.MAX_VALUE);
2666 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2667 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002668 reset(getServices().powerManagerInternal);
2669 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002670
2671 dpm.setMaximumTimeToLock(admin2, 10);
Pavel Grafov28939982017-10-03 15:11:52 +01002672 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2673 verifyStayOnWhilePluggedCleared(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002674 reset(getServices().powerManagerInternal);
2675 reset(getServices().settings);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002676
Pavel Grafov28939982017-10-03 15:11:52 +01002677 // There's no restriction; should be set to MAX.
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002678 dpm.setMaximumTimeToLock(admin2, 0);
Pavel Grafov28939982017-10-03 15:11:52 +01002679 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2680 verifyStayOnWhilePluggedCleared(false);
2681 }
2682
Varun Shahb472b8f2019-09-23 23:01:06 -07002683 public void testIsActiveSupervisionApp() throws Exception {
2684 when(mServiceContext.resources
2685 .getString(R.string.config_defaultSupervisionProfileOwnerComponent))
2686 .thenReturn(admin1.flattenToString());
2687
2688 final int PROFILE_USER = 15;
2689 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2690 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2691 mContext.binder.callingUid = PROFILE_ADMIN;
2692
2693 final DevicePolicyManagerInternal dpmi =
2694 LocalServices.getService(DevicePolicyManagerInternal.class);
2695 assertTrue(dpmi.isActiveSupervisionApp(PROFILE_ADMIN));
2696 }
2697
Pavel Grafov28939982017-10-03 15:11:52 +01002698 // Test if lock timeout on managed profile is handled correctly depending on whether profile
2699 // uses separate challenge.
2700 public void testSetMaximumTimeToLockProfile() throws Exception {
2701 final int PROFILE_USER = 15;
2702 final int PROFILE_ADMIN = UserHandle.getUid(PROFILE_USER, 19436);
2703 addManagedProfile(admin1, PROFILE_ADMIN, admin1);
2704 mContext.binder.callingUid = PROFILE_ADMIN;
2705 final DevicePolicyManagerInternal dpmi =
2706 LocalServices.getService(DevicePolicyManagerInternal.class);
2707
2708 dpm.setMaximumTimeToLock(admin1, 0);
2709
2710 reset(getServices().powerManagerInternal);
2711 reset(getServices().settings);
2712
2713 // First add timeout for the profile.
2714 dpm.setMaximumTimeToLock(admin1, 10);
2715 verifyScreenTimeoutCall(10L, UserHandle.USER_SYSTEM);
2716
2717 reset(getServices().powerManagerInternal);
2718 reset(getServices().settings);
2719
2720 // Add separate challenge
2721 when(getServices().lockPatternUtils
2722 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(true);
2723 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
2724
2725 verifyScreenTimeoutCall(10L, PROFILE_USER);
2726 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
2727
2728 reset(getServices().powerManagerInternal);
2729 reset(getServices().settings);
2730
2731 // Remove the timeout.
2732 dpm.setMaximumTimeToLock(admin1, 0);
2733 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2734 verifyScreenTimeoutCall(null , UserHandle.USER_SYSTEM);
2735
2736 reset(getServices().powerManagerInternal);
2737 reset(getServices().settings);
2738
2739 // Add it back.
2740 dpm.setMaximumTimeToLock(admin1, 10);
2741 verifyScreenTimeoutCall(10L, PROFILE_USER);
2742 verifyScreenTimeoutCall(null, UserHandle.USER_SYSTEM);
2743
2744 reset(getServices().powerManagerInternal);
2745 reset(getServices().settings);
2746
2747 // Remove separate challenge.
2748 reset(getServices().lockPatternUtils);
2749 when(getServices().lockPatternUtils
2750 .isSeparateProfileChallengeEnabled(eq(PROFILE_USER))).thenReturn(false);
2751 dpmi.reportSeparateProfileChallengeChanged(PROFILE_USER);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01002752 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(true);
Pavel Grafov28939982017-10-03 15:11:52 +01002753
2754 verifyScreenTimeoutCall(Long.MAX_VALUE, PROFILE_USER);
2755 verifyScreenTimeoutCall(10L , UserHandle.USER_SYSTEM);
2756
2757 reset(getServices().powerManagerInternal);
2758 reset(getServices().settings);
2759
2760 // Remove the timeout.
2761 dpm.setMaximumTimeToLock(admin1, 0);
2762 verifyScreenTimeoutCall(null, PROFILE_USER);
2763 verifyScreenTimeoutCall(Long.MAX_VALUE, UserHandle.USER_SYSTEM);
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002764 }
2765
Michal Karpinski943aabd2016-10-06 11:09:25 +01002766 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2767 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2768 setupDeviceOwner();
2769 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2770
Michal Karpinskid084ca52017-01-18 15:54:18 +00002771 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2772 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2773 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2774 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2775 - ONE_MINUTE;
2776
2777 // verify that the minimum timeout cannot be modified on user builds (system property is
2778 // not being read)
Pavel Grafov75c0a892017-05-18 17:28:27 +01002779 getServices().buildMock.isDebuggable = false;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002780
2781 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2782 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2783 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2784
Pavel Grafov75c0a892017-05-18 17:28:27 +01002785 verify(getServices().systemProperties, never()).getLong(anyString(), anyLong());
Michal Karpinskid084ca52017-01-18 15:54:18 +00002786
2787 // restore to the debuggable build state
Pavel Grafov75c0a892017-05-18 17:28:27 +01002788 getServices().buildMock.isDebuggable = true;
Michal Karpinskid084ca52017-01-18 15:54:18 +00002789
Michal Karpinskid084ca52017-01-18 15:54:18 +00002790 // reset to default (0 means the admin is not participating, so default should be returned)
2791 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002792
2793 // aggregation should be the default if unset by any admin
2794 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2795 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2796
2797 // admin not participating by default
2798 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2799
2800 //clamping from the top
2801 dpm.setRequiredStrongAuthTimeout(admin1,
2802 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2803 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2804 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2805 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2806 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2807
Michal Karpinskid084ca52017-01-18 15:54:18 +00002808 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002809 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2810 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2811 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2812 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2813
2814 // clamping from the bottom
2815 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2816 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2817 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2818
Michal Karpinskid084ca52017-01-18 15:54:18 +00002819 // values within range
2820 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2821 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2822 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2823
2824 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2825 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2826 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002827
2828 // reset to default
2829 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2830 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2831 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2832 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2833
2834 // negative value
Pavel Grafova1ea8d92017-05-25 21:55:24 +01002835 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
2836 () -> dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE));
Michal Karpinski943aabd2016-10-06 11:09:25 +01002837 }
2838
Pavel Grafov28939982017-10-03 15:11:52 +01002839 private void verifyScreenTimeoutCall(Long expectedTimeout, int userId) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002840 if (expectedTimeout == null) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002841 verify(getServices().powerManagerInternal, times(0))
Pavel Grafov28939982017-10-03 15:11:52 +01002842 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), anyLong());
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002843 } else {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002844 verify(getServices().powerManagerInternal, times(1))
Pavel Grafov28939982017-10-03 15:11:52 +01002845 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(userId), eq(expectedTimeout));
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002846 }
Pavel Grafov28939982017-10-03 15:11:52 +01002847 }
2848
2849 private void verifyStayOnWhilePluggedCleared(boolean cleared) {
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002850 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2851 // UnfinishedVerificationException.
2852 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002853
Esteban Talavera01576862016-12-15 11:16:44 +00002854 private void setup_DeviceAdminFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002855 when(getServices().packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
Victor Chang3e794af2016-03-04 13:48:17 +00002856 .thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002857 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002858 .thenReturn(false);
2859 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002860 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2861 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002862 .thenReturn(true);
2863 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2864
2865 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002866 }
Victor Chang3e794af2016-03-04 13:48:17 +00002867
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002868 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2869 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002870 mContext.packageName = admin1.getPackageName();
2871 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002872 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2873 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2874 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2875 false);
2876 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2877 }
2878
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002879 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2880 setup_DeviceAdminFeatureOff();
2881 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2882 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2883 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2884 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2885 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2886 assertCheckProvisioningPreCondition(
2887 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2888 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2889 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2890 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2891 }
2892
Esteban Talavera01576862016-12-15 11:16:44 +00002893 private void setup_ManagedProfileFeatureOff() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002894 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002895 .thenReturn(false);
2896 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01002897 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2898 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002899 .thenReturn(true);
2900 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2901
2902 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002903 }
Victor Chang3e794af2016-03-04 13:48:17 +00002904
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002905 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2906 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002907 mContext.packageName = admin1.getPackageName();
2908 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002909 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2910 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2911 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2912 false);
2913 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2914
2915 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002916 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Victor Chang3e794af2016-03-04 13:48:17 +00002917 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2918 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2919 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2920 true);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2922 }
2923
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002924 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2925 setup_ManagedProfileFeatureOff();
2926 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2927 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2928 DevicePolicyManager.CODE_OK);
2929 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2930 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2931 assertCheckProvisioningPreCondition(
2932 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2933 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2934 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2935 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2936
2937 // Test again when split user is on
Pavel Grafov75c0a892017-05-18 17:28:27 +01002938 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002939 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2940 DevicePolicyManager.CODE_OK);
2941 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2942 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2943 assertCheckProvisioningPreCondition(
2944 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2945 DevicePolicyManager.CODE_OK);
2946 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2947 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2948 }
2949
Esteban Talavera01576862016-12-15 11:16:44 +00002950 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002951 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002952 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002953 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2954 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002955 .thenReturn(true);
2956 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2957
2958 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002959 }
Victor Chang3e794af2016-03-04 13:48:17 +00002960
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002961 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2962 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002963 mContext.packageName = admin1.getPackageName();
2964 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002965 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2966 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2967 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2968 false /* because of non-split user */);
2969 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2970 false /* because of non-split user */);
2971 }
2972
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002973 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002974 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002975 setup_nonSplitUser_firstBoot_primaryUser();
2976 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2977 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2978 DevicePolicyManager.CODE_OK);
2979 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2980 DevicePolicyManager.CODE_OK);
2981 assertCheckProvisioningPreCondition(
2982 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2983 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2984 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2985 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2986 }
2987
Esteban Talavera01576862016-12-15 11:16:44 +00002988 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01002989 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00002990 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01002991 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(false);
2992 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00002993 .thenReturn(true);
2994 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2995
2996 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002997 }
Victor Chang3e794af2016-03-04 13:48:17 +00002998
Nicolas Prevot45d29072017-01-18 16:11:19 +00002999 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
3000 setDeviceOwner();
3001 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3002 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
3003 }
3004
3005 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
3006 setup_nonSplitUser_withDo_primaryUser();
3007 final int MANAGED_PROFILE_USER_ID = 18;
3008 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
3009 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003010 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003011 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003012 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003013 true)).thenReturn(true);
3014 }
3015
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003016 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
3017 throws Exception {
3018 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003019 mContext.packageName = admin1.getPackageName();
3020 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003021 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3022 false/* because of completed device setup */);
3023 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3025 false/* because of non-split user */);
3026 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3027 false/* because of non-split user */);
3028 }
3029
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003030 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
3031 throws Exception {
3032 setup_nonSplitUser_afterDeviceSetup_primaryUser();
3033 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3034 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3035 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3036 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3037 DevicePolicyManager.CODE_OK);
3038 assertCheckProvisioningPreCondition(
3039 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3040 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3041 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3042 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
3043 }
3044
Nicolas Prevot45d29072017-01-18 16:11:19 +00003045 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
3046 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003047 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00003048 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3049
3050 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3051 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003052 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00003053
3054 // COMP mode is allowed.
3055 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3056 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003057 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003058
Nicolas Prevot45d29072017-01-18 16:11:19 +00003059 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00003060 assertCheckProvisioningPreCondition(
3061 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003062 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003063 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003064 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3065 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3066 }
Esteban Talavera01576862016-12-15 11:16:44 +00003067
Nicolas Prevot45d29072017-01-18 16:11:19 +00003068 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
3069 setup_nonSplitUser_withDo_primaryUser();
3070 mContext.packageName = admin1.getPackageName();
3071 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3072 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
3073 // other packages should be forbidden.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003074 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003075 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3076 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3077 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003078 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003079 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3080 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3081 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3082 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3083 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003084 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003085 assertCheckProvisioningPreCondition(
3086 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003087 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003088 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003089 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3090 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3091 }
Esteban Talavera01576862016-12-15 11:16:44 +00003092
Nicolas Prevot45d29072017-01-18 16:11:19 +00003093 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
3094 throws Exception {
3095 setup_nonSplitUser_withDo_primaryUser();
3096 mContext.packageName = admin1.getPackageName();
3097 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003098 // The DO should not be allowed to initiate provisioning if the restriction is set by
3099 // another entity.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003100 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003101 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3102 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3103 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003104 when(getServices().userManager.getUserRestrictionSource(
Esteban Talavera01576862016-12-15 11:16:44 +00003105 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
3106 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
3107 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3108 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3109 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003110 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3111
3112 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00003113 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00003114 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00003115 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003116 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3117 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3118 }
3119
3120 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
3121 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3122 mContext.packageName = admin1.getPackageName();
3123 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3124
3125 // We can delete the managed profile to create a new one, so provisioning is allowed.
3126 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3127 DevicePolicyManager.CODE_OK);
3128 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3129 assertCheckProvisioningPreCondition(
3130 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3131 DpmMockContext.ANOTHER_PACKAGE_NAME,
3132 DevicePolicyManager.CODE_OK);
3133 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
3134 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
3135 }
3136
3137 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
3138 throws Exception {
3139 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
3140 mContext.packageName = admin1.getPackageName();
3141 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003142 when(getServices().userManager.hasUserRestriction(
Nicolas Prevot45d29072017-01-18 16:11:19 +00003143 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3144 eq(UserHandle.SYSTEM)))
3145 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003146 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003147 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3148 eq(UserHandle.SYSTEM)))
3149 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00003150
3151 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00003152 assertCheckProvisioningPreCondition(
3153 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3154 DpmMockContext.ANOTHER_PACKAGE_NAME,
3155 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3156 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
3157 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00003158
3159 // But the device owner can still do it because it has set the restriction itself.
3160 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3161 DevicePolicyManager.CODE_OK);
3162 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00003163 }
3164
3165 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003166 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003167 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003168 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3169 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003170 .thenReturn(false);
3171 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
3172
3173 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003174 }
Victor Chang3e794af2016-03-04 13:48:17 +00003175
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003176 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
3177 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003178 mContext.packageName = admin1.getPackageName();
3179 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003180 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3181 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3182 false /* because canAddMoreManagedProfiles returns false */);
3183 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3184 true);
3185 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3186 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00003187 }
3188
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003189 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
3190 throws Exception {
3191 setup_splitUser_firstBoot_systemUser();
3192 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3193 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3194 DevicePolicyManager.CODE_OK);
3195 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003196 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003197 assertCheckProvisioningPreCondition(
3198 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3199 DevicePolicyManager.CODE_OK);
3200 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3201 DevicePolicyManager.CODE_SYSTEM_USER);
3202 }
3203
Esteban Talavera01576862016-12-15 11:16:44 +00003204 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003205 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003206 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003207 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3208 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003209 .thenReturn(false);
3210 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3211
3212 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003213 }
Victor Chang3e794af2016-03-04 13:48:17 +00003214
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003215 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
3216 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003217 mContext.packageName = admin1.getPackageName();
3218 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003219 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3220 true/* it's undefined behavior. Can be changed into false in the future */);
3221 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3222 false /* because canAddMoreManagedProfiles returns false */);
3223 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3224 true/* it's undefined behavior. Can be changed into false in the future */);
3225 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3226 false/* because calling uid is system user */);
3227 }
3228
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003229 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
3230 throws Exception {
3231 setup_splitUser_afterDeviceSetup_systemUser();
3232 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3233 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3234 DevicePolicyManager.CODE_OK);
3235 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003236 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003237 assertCheckProvisioningPreCondition(
3238 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3239 DevicePolicyManager.CODE_OK);
3240 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3241 DevicePolicyManager.CODE_SYSTEM_USER);
3242 }
3243
Esteban Talavera01576862016-12-15 11:16:44 +00003244 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003245 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003246 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003247 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3248 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003249 true)).thenReturn(true);
3250 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3251
3252 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003253 }
Victor Chang3e794af2016-03-04 13:48:17 +00003254
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003255 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
3256 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003257 mContext.packageName = admin1.getPackageName();
3258 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003259 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
3260 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3261 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3262 true);
3263 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00003264 }
3265
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003266 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003267 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003268 setup_splitUser_firstBoot_primaryUser();
3269 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3270 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3271 DevicePolicyManager.CODE_OK);
3272 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3273 DevicePolicyManager.CODE_OK);
3274 assertCheckProvisioningPreCondition(
3275 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3276 DevicePolicyManager.CODE_OK);
3277 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3278 DevicePolicyManager.CODE_OK);
3279 }
3280
Esteban Talavera01576862016-12-15 11:16:44 +00003281 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003282 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003283 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003284 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3285 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003286 true)).thenReturn(true);
3287 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
3288
3289 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003290 }
Victor Chang3e794af2016-03-04 13:48:17 +00003291
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003292 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
3293 throws Exception {
3294 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003295 mContext.packageName = admin1.getPackageName();
3296 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003297 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3298 true/* it's undefined behavior. Can be changed into false in the future */);
3299 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3300 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3301 true/* it's undefined behavior. Can be changed into false in the future */);
3302 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3303 false/* because user setup completed */);
3304 }
3305
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003306 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003307 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003308 setup_splitUser_afterDeviceSetup_primaryUser();
3309 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3310 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
3311 DevicePolicyManager.CODE_OK);
3312 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3313 DevicePolicyManager.CODE_OK);
3314 assertCheckProvisioningPreCondition(
3315 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3316 DevicePolicyManager.CODE_OK);
3317 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3318 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3319 }
3320
Esteban Talavera01576862016-12-15 11:16:44 +00003321 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003322 setDeviceOwner();
3323
Pavel Grafov75c0a892017-05-18 17:28:27 +01003324 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003325 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003326 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3327 when(getServices().userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
Victor Chang3e794af2016-03-04 13:48:17 +00003328 .thenReturn(false);
3329 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3330
3331 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003332 }
Victor Chang3e794af2016-03-04 13:48:17 +00003333
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003334 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3335 throws Exception {
3336 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003337 mContext.packageName = admin1.getPackageName();
3338 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003339 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3340 false /* can't provision managed profile on system user */);
3341 }
3342
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003343 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003344 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003345 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3346 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3347 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3348 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3349 }
3350
3351 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003352 setDeviceOwner();
3353
Pavel Grafov75c0a892017-05-18 17:28:27 +01003354 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Victor Chang3e794af2016-03-04 13:48:17 +00003355 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003356 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3357 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Victor Chang3e794af2016-03-04 13:48:17 +00003358 true)).thenReturn(true);
3359 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3360
3361 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003362 }
Victor Chang3e794af2016-03-04 13:48:17 +00003363
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003364 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3365 throws Exception {
3366 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003367 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3368 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003369 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3370 }
3371
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003372 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003373 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003374 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3375 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003376
3377 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003378 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3379 DevicePolicyManager.CODE_OK);
3380 }
3381
3382 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003383 setDeviceOwner();
3384
Pavel Grafov75c0a892017-05-18 17:28:27 +01003385 when(getServices().ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003386 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003387 when(getServices().userManagerForMock.isSplitSystemUser()).thenReturn(true);
3388 when(getServices().userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003389 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3390 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003391 .thenReturn(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003392 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003393 false /* we can't remove a managed profile */)).thenReturn(false);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003394 when(getServices().userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Nicolas Prevot56400a42016-11-10 12:57:54 +00003395 true)).thenReturn(true);
3396 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3397
3398 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003399 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003400
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003401 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3402 throws Exception {
3403 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003404 mContext.packageName = admin1.getPackageName();
3405 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003406 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3407 }
3408
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003409 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3410 throws Exception {
3411 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3412 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3413 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3414 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3415 }
3416
3417 public void testCheckProvisioningPreCondition_permission() {
3418 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003419 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3420 () -> dpm.checkProvisioningPreCondition(
3421 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package"));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003422 }
3423
Victor Chang3577ed22016-08-25 18:49:26 +01003424 public void testForceUpdateUserSetupComplete_permission() {
3425 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003426 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3427 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003428 }
3429
3430 public void testForceUpdateUserSetupComplete_systemUser() {
3431 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3432 // GIVEN calling from user 20
3433 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01003434 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3435 () -> dpm.forceUpdateUserSetupComplete());
Victor Chang3577ed22016-08-25 18:49:26 +01003436 }
3437
3438 public void testForceUpdateUserSetupComplete_userbuild() {
3439 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3440 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3441
3442 final int userId = UserHandle.USER_SYSTEM;
3443 // GIVEN userComplete is false in SettingsProvider
3444 setUserSetupCompleteForUser(false, userId);
3445
3446 // GIVEN userComplete is true in DPM
3447 DevicePolicyManagerService.DevicePolicyData userData =
3448 new DevicePolicyManagerService.DevicePolicyData(userId);
3449 userData.mUserSetupComplete = true;
3450 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3451
3452 // GIVEN it's user build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003453 getServices().buildMock.isDebuggable = false;
Victor Chang3577ed22016-08-25 18:49:26 +01003454
3455 assertTrue(dpms.hasUserSetupCompleted());
3456
3457 dpm.forceUpdateUserSetupComplete();
3458
3459 // THEN the state in dpms is not changed
3460 assertTrue(dpms.hasUserSetupCompleted());
3461 }
3462
3463 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3464 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3465 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3466
3467 final int userId = UserHandle.USER_SYSTEM;
3468 // GIVEN userComplete is false in SettingsProvider
3469 setUserSetupCompleteForUser(false, userId);
3470
3471 // GIVEN userComplete is true in DPM
3472 DevicePolicyManagerService.DevicePolicyData userData =
3473 new DevicePolicyManagerService.DevicePolicyData(userId);
3474 userData.mUserSetupComplete = true;
3475 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3476
3477 // GIVEN it's userdebug build
Pavel Grafov75c0a892017-05-18 17:28:27 +01003478 getServices().buildMock.isDebuggable = true;
Victor Chang3577ed22016-08-25 18:49:26 +01003479
3480 assertTrue(dpms.hasUserSetupCompleted());
3481
3482 dpm.forceUpdateUserSetupComplete();
3483
3484 // THEN the state in dpms is not changed
3485 assertFalse(dpms.hasUserSetupCompleted());
3486 }
3487
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003488 private void clearDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01003489 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(getServices().packageManager)
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003490 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01003491
3492 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3493 runAsCaller(mAdmin1Context, dpms, dpm -> {
3494 dpm.clearDeviceOwnerApp(admin1.getPackageName());
3495 });
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003496 }
3497
3498 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3499 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3500 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003501
3502 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3503 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003504 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003505 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3506 .thenReturn(true);
3507
3508 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003509 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003510
3511 // Enabling logging should not change the timestamp.
3512 dpm.setSecurityLoggingEnabled(admin1, true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003513 verify(getServices().settings)
Esteban Talaverad36dd152016-12-15 08:51:45 +00003514 .securityLogSetLoggingEnabledProperty(true);
Pavel Grafov75c0a892017-05-18 17:28:27 +01003515 when(getServices().settings.securityLogGetLoggingEnabledProperty())
Esteban Talaverad36dd152016-12-15 08:51:45 +00003516 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003517 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003518
3519 // Retrieving the logs should update the timestamp.
3520 final long beforeRetrieval = System.currentTimeMillis();
3521 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003522 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003523 final long afterRetrieval = System.currentTimeMillis();
3524 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3525 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3526
3527 // Retrieving the pre-boot logs should update the timestamp.
3528 Thread.sleep(2);
3529 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003530 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003531 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3532
3533 // Checking the timestamp again should not change it.
3534 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003535 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003536
3537 // Retrieving the logs again should update the timestamp.
3538 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003539 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003540 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3541
3542 // Disabling logging should not change the timestamp.
3543 Thread.sleep(2);
3544 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003545 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003546
3547 // Restarting the DPMS should not lose the timestamp.
3548 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003549 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003550
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003551 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3552 mContext.binder.callingUid = 1234567;
3553 mContext.callerPermissions.add(permission.MANAGE_USERS);
3554 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3555 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3556
3557 // System can retrieve the timestamp.
3558 mContext.binder.clearCallingIdentity();
3559 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3560
3561 // Removing the device owner should clear the timestamp.
3562 clearDeviceOwner();
3563 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003564 }
3565
yuemingw0de748d2017-11-15 19:22:27 +00003566 public void testSetSystemSettingFailWithNonWhitelistedSettings() throws Exception {
3567 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3568 setupDeviceOwner();
3569 assertExpectException(SecurityException.class, null, () ->
3570 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS_FOR_VR, "0"));
3571 }
3572
yuemingwc0281f12018-03-28 15:58:49 +01003573 public void testSetSystemSettingWithDO() throws Exception {
yuemingw0de748d2017-11-15 19:22:27 +00003574 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3575 setupDeviceOwner();
3576 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
yuemingwc0281f12018-03-28 15:58:49 +01003577 verify(getServices().settings).settingsSystemPutStringForUser(
3578 Settings.System.SCREEN_BRIGHTNESS, "0", UserHandle.USER_SYSTEM);
3579 }
3580
3581 public void testSetSystemSettingWithPO() throws Exception {
3582 setupProfileOwner();
3583 dpm.setSystemSetting(admin1, Settings.System.SCREEN_BRIGHTNESS, "0");
3584 verify(getServices().settings).settingsSystemPutStringForUser(
3585 Settings.System.SCREEN_BRIGHTNESS, "0", DpmMockContext.CALLER_USER_HANDLE);
yuemingw0de748d2017-11-15 19:22:27 +00003586 }
3587
yuemingwe43cdf72017-10-12 16:52:11 +01003588 public void testSetTime() throws Exception {
3589 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3590 setupDeviceOwner();
3591 dpm.setTime(admin1, 0);
Neil Fullere3767562019-11-23 11:33:57 +00003592
3593 BaseMatcher<ManualTimeSuggestion> hasZeroTime = new BaseMatcher<ManualTimeSuggestion>() {
3594 @Override
3595 public boolean matches(Object item) {
3596 final ManualTimeSuggestion suggestion = (ManualTimeSuggestion) item;
3597 return suggestion.getUtcTime().getValue() == 0;
3598 }
3599 @Override
3600 public void describeTo(Description description) {
3601 description.appendText("ManualTimeSuggestion{utcTime.value=0}");
3602 }
3603 };
3604 verify(getServices().timeDetector).suggestManualTime(argThat(hasZeroTime));
yuemingwe43cdf72017-10-12 16:52:11 +01003605 }
3606
3607 public void testSetTimeFailWithPO() throws Exception {
3608 setupProfileOwner();
3609 assertExpectException(SecurityException.class, null, () -> dpm.setTime(admin1, 0));
3610 }
3611
3612 public void testSetTimeWithAutoTimeOn() throws Exception {
3613 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3614 setupDeviceOwner();
3615 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME, 0))
3616 .thenReturn(1);
3617 assertFalse(dpm.setTime(admin1, 0));
3618 }
3619
3620 public void testSetTimeZone() throws Exception {
3621 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3622 setupDeviceOwner();
3623 dpm.setTimeZone(admin1, "Asia/Shanghai");
3624 verify(getServices().alarmManager).setTimeZone("Asia/Shanghai");
3625 }
3626
3627 public void testSetTimeZoneFailWithPO() throws Exception {
3628 setupProfileOwner();
3629 assertExpectException(SecurityException.class, null,
3630 () -> dpm.setTimeZone(admin1, "Asia/Shanghai"));
3631 }
3632
3633 public void testSetTimeZoneWithAutoTimeZoneOn() throws Exception {
3634 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3635 setupDeviceOwner();
3636 when(getServices().settings.settingsGlobalGetInt(Settings.Global.AUTO_TIME_ZONE, 0))
3637 .thenReturn(1);
3638 assertFalse(dpm.setTimeZone(admin1, "Asia/Shanghai"));
3639 }
3640
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003641 public void testGetLastBugReportRequestTime() throws Exception {
3642 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3643 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003644
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003645 mContext.packageName = admin1.getPackageName();
3646 mContext.applicationInfo = new ApplicationInfo();
3647 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3648 .thenReturn(Color.WHITE);
3649 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3650 anyObject())).thenReturn(Color.WHITE);
3651
Esteban Talaverad36dd152016-12-15 08:51:45 +00003652 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3653 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003654 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003655
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003656 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003657 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003658
3659 // Requesting a bug report should update the timestamp.
3660 final long beforeRequest = System.currentTimeMillis();
3661 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003662 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003663 final long afterRequest = System.currentTimeMillis();
3664 assertTrue(bugReportRequestTime >= beforeRequest);
3665 assertTrue(bugReportRequestTime <= afterRequest);
3666
3667 // Checking the timestamp again should not change it.
3668 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003669 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003670
3671 // Restarting the DPMS should not lose the timestamp.
3672 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003673 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003674
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003675 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3676 mContext.binder.callingUid = 1234567;
3677 mContext.callerPermissions.add(permission.MANAGE_USERS);
3678 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3679 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3680
3681 // System can retrieve the timestamp.
3682 mContext.binder.clearCallingIdentity();
3683 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3684
3685 // Removing the device owner should clear the timestamp.
3686 clearDeviceOwner();
3687 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003688 }
3689
3690 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3691 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3692 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003693 mContext.packageName = admin1.getPackageName();
3694 mContext.applicationInfo = new ApplicationInfo();
3695 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3696 .thenReturn(Color.WHITE);
3697 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3698 anyObject())).thenReturn(Color.WHITE);
3699
3700 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3701 // feature is disabled because there are non-affiliated secondary users.
Pavel Grafov75c0a892017-05-18 17:28:27 +01003702 getServices().removeUser(DpmMockContext.CALLER_USER_HANDLE);
Ricky Wai1a6e6672017-10-27 14:46:01 +01003703 when(getServices().iipConnectivityMetrics.addNetdEventCallback(anyInt(), anyObject()))
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003704 .thenReturn(true);
3705
3706 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003707 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003708
3709 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3710 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003711 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003712
3713 // Enabling logging should not change the timestamp.
3714 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003715 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003716
3717 // Retrieving the logs should update the timestamp.
3718 final long beforeRetrieval = System.currentTimeMillis();
3719 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003720 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003721 final long afterRetrieval = System.currentTimeMillis();
3722 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3723 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3724
3725 // Checking the timestamp again should not change it.
3726 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003727 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003728
3729 // Retrieving the logs again should update the timestamp.
3730 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003731 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003732 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3733
3734 // Disabling logging should not change the timestamp.
3735 Thread.sleep(2);
3736 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003737 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003738
3739 // Restarting the DPMS should not lose the timestamp.
3740 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003741 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3742
3743 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3744 mContext.binder.callingUid = 1234567;
3745 mContext.callerPermissions.add(permission.MANAGE_USERS);
3746 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3747 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3748
3749 // System can retrieve the timestamp.
3750 mContext.binder.clearCallingIdentity();
3751 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3752
3753 // Removing the device owner should clear the timestamp.
3754 clearDeviceOwner();
3755 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003756 }
3757
Tony Mak2f26b792016-11-28 17:54:51 +00003758 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3759 // Setup device owner.
3760 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3761 setupDeviceOwner();
3762
3763 // Only device owner is setup, the result list should be empty.
3764 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3765 MoreAsserts.assertEmpty(targetUsers);
3766
3767 // Setup a managed profile managed by the same admin.
3768 final int MANAGED_PROFILE_USER_ID = 15;
3769 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3770 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3771
3772 // Add a secondary user, it should never talk with.
3773 final int ANOTHER_USER_ID = 36;
Pavel Grafov75c0a892017-05-18 17:28:27 +01003774 getServices().addUser(ANOTHER_USER_ID, 0);
Tony Mak2f26b792016-11-28 17:54:51 +00003775
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003776 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3777 // other.
3778 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3779 MoreAsserts.assertEmpty(targetUsers);
3780
3781 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3782 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3783 MoreAsserts.assertEmpty(targetUsers);
3784
3785 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003786 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003787 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3788 dpm.setAffiliationIds(admin1, userAffiliationIds);
3789
3790 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3791 dpm.setAffiliationIds(admin1, userAffiliationIds);
3792
Tony Mak2f26b792016-11-28 17:54:51 +00003793 // Calling from device owner admin, the result list should just contain the managed
3794 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003795 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003796 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3797 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3798
3799 // Calling from managed profile admin, the result list should just contain the system
3800 // user id.
3801 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3802 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3803 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003804
3805 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003806 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003807
3808 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3809 // to each other.
3810 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3811 MoreAsserts.assertEmpty(targetUsers);
3812
3813 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3814 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3815 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003816 }
3817
3818 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3819 // Setup a device owner.
3820 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3821 setupDeviceOwner();
3822
3823 // Set up a managed profile managed by different package.
3824 final int MANAGED_PROFILE_USER_ID = 15;
3825 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3826 final ComponentName adminDifferentPackage =
3827 new ComponentName("another.package", "whatever.class");
3828 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3829
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003830 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003831 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003832 dpm.setAffiliationIds(admin1, userAffiliationIds);
3833
3834 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3835 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3836
Tony Mak2f26b792016-11-28 17:54:51 +00003837 // Calling from device owner admin, we should get zero bind device admin target users as
3838 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003839 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003840 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3841 MoreAsserts.assertEmpty(targetUsers);
3842
3843 // Calling from managed profile admin, we should still get zero target users for the same
3844 // reason.
3845 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3846 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3847 MoreAsserts.assertEmpty(targetUsers);
3848 }
3849
Jason Parks3c13b642017-11-28 15:39:43 -06003850 private void verifyLockTaskState(int userId) throws Exception {
Benjamin Franz78ae1062018-03-26 11:01:32 +01003851 verifyLockTaskState(userId, new String[0],
3852 DevicePolicyManager.LOCK_TASK_FEATURE_GLOBAL_ACTIONS);
Jason Parks3c13b642017-11-28 15:39:43 -06003853 }
3854
3855 private void verifyLockTaskState(int userId, String[] packages, int flags) throws Exception {
3856 verify(getServices().iactivityManager).updateLockTaskPackages(userId, packages);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003857 verify(getServices().iactivityTaskManager).updateLockTaskFeatures(userId, flags);
Jason Parks3c13b642017-11-28 15:39:43 -06003858 }
3859
3860 private void verifyCanSetLockTask(int uid, int userId, ComponentName who, String[] packages,
3861 int flags) throws Exception {
3862 mContext.binder.callingUid = uid;
3863 dpm.setLockTaskPackages(who, packages);
3864 MoreAsserts.assertEquals(packages, dpm.getLockTaskPackages(who));
3865 for (String p : packages) {
3866 assertTrue(dpm.isLockTaskPermitted(p));
3867 }
3868 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3869 // Test to see if set lock task features can be set
3870 dpm.setLockTaskFeatures(who, flags);
3871 verifyLockTaskState(userId, packages, flags);
3872 }
3873
3874 private void verifyCanNotSetLockTask(int uid, ComponentName who, String[] packages,
3875 int flags) throws Exception {
3876 mContext.binder.callingUid = uid;
3877 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3878 () -> dpm.setLockTaskPackages(who, packages));
3879 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3880 () -> dpm.getLockTaskPackages(who));
3881 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3882 assertExpectException(SecurityException.class, /* messageRegex =*/ null,
3883 () -> dpm.setLockTaskFeatures(who, flags));
3884 }
3885
Charles Hee078db72017-10-19 18:03:20 +01003886 public void testLockTaskPolicyAllowedForAffiliatedUsers() throws Exception {
Esteban Talaverabdcada92017-02-01 14:20:06 +00003887 // Setup a device owner.
3888 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3889 setupDeviceOwner();
Charles Hee078db72017-10-19 18:03:20 +01003890 // Lock task policy is updated when loading user data.
Jason Parks3c13b642017-11-28 15:39:43 -06003891 verifyLockTaskState(UserHandle.USER_SYSTEM);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003892
3893 // Set up a managed profile managed by different package (package name shouldn't matter)
3894 final int MANAGED_PROFILE_USER_ID = 15;
3895 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3896 final ComponentName adminDifferentPackage =
3897 new ComponentName("another.package", "whatever.class");
3898 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
Jason Parks3c13b642017-11-28 15:39:43 -06003899 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3900
3901 // Setup a PO on the secondary user
3902 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3903 setAsProfileOwner(admin3);
3904 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003905
3906 // The DO can still set lock task packages
Esteban Talaverabdcada92017-02-01 14:20:06 +00003907 final String[] doPackages = {"doPackage1", "doPackage2"};
Jason Parks3c13b642017-11-28 15:39:43 -06003908 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003909 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3910 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003911 verifyCanSetLockTask(DpmMockContext.CALLER_SYSTEM_USER_UID, UserHandle.USER_SYSTEM, admin1, doPackages, flags);
3912
3913 final String[] secondaryPoPackages = {"secondaryPoPackage1", "secondaryPoPackage2"};
3914 final int secondaryPoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003915 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3916 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003917 verifyCanNotSetLockTask(DpmMockContext.CALLER_UID, admin3, secondaryPoPackages, secondaryPoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003918
3919 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3920 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3921 final String[] poPackages = {"poPackage1", "poPackage2"};
Charles Hee078db72017-10-19 18:03:20 +01003922 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003923 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3924 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003925 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003926
3927 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003928 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003929 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3930 dpm.setAffiliationIds(admin1, userAffiliationIds);
3931
3932 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3933 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3934
3935 // Now the managed profile can set lock task packages.
3936 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3937 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3938 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3939 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
Charles Hee078db72017-10-19 18:03:20 +01003940 // And it can set lock task features.
3941 dpm.setLockTaskFeatures(adminDifferentPackage, poFlags);
Jason Parks3c13b642017-11-28 15:39:43 -06003942 verifyLockTaskState(MANAGED_PROFILE_USER_ID, poPackages, poFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003943
3944 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003945 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003946 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3947 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
Charles Hee078db72017-10-19 18:03:20 +01003948 verify(getServices().iactivityManager, times(2)).updateLockTaskPackages(
3949 MANAGED_PROFILE_USER_ID, new String[0]);
Wale Ogunwale04d9cb52018-04-30 13:55:07 -07003950 verify(getServices().iactivityTaskManager, times(2)).updateLockTaskFeatures(
Charles Hee078db72017-10-19 18:03:20 +01003951 MANAGED_PROFILE_USER_ID, DevicePolicyManager.LOCK_TASK_FEATURE_NONE);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003952
Jason Parks3c13b642017-11-28 15:39:43 -06003953 // Verify that lock task packages were not cleared for the DO
Esteban Talaverabdcada92017-02-01 14:20:06 +00003954 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3955 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
Jason Parks3c13b642017-11-28 15:39:43 -06003956
3957 }
3958
3959 public void testLockTaskPolicyForProfileOwner() throws Exception {
3960 // Setup a PO
3961 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3962 setAsProfileOwner(admin1);
3963 verifyLockTaskState(DpmMockContext.CALLER_USER_HANDLE);
3964
3965 final String[] poPackages = {"poPackage1", "poPackage2"};
3966 final int poFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003967 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3968 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003969 verifyCanSetLockTask(DpmMockContext.CALLER_UID, DpmMockContext.CALLER_USER_HANDLE, admin1,
3970 poPackages, poFlags);
3971
3972 // Set up a managed profile managed by different package (package name shouldn't matter)
3973 final int MANAGED_PROFILE_USER_ID = 15;
3974 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3975 final ComponentName adminDifferentPackage =
3976 new ComponentName("another.package", "whatever.class");
3977 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3978 verifyLockTaskState(MANAGED_PROFILE_USER_ID);
3979
3980 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3981 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3982 final String[] mpoPackages = {"poPackage1", "poPackage2"};
3983 final int mpoFlags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
Benjamin Franzcaffa772018-02-05 16:36:10 +00003984 | DevicePolicyManager.LOCK_TASK_FEATURE_HOME
3985 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
Jason Parks3c13b642017-11-28 15:39:43 -06003986 verifyCanNotSetLockTask(MANAGED_PROFILE_ADMIN_UID, adminDifferentPackage, mpoPackages, mpoFlags);
Esteban Talaverabdcada92017-02-01 14:20:06 +00003987 }
3988
Benjamin Franzcaffa772018-02-05 16:36:10 +00003989 public void testLockTaskFeatures_IllegalArgumentException() throws Exception {
3990 // Setup a device owner.
3991 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3992 setupDeviceOwner();
3993 // Lock task policy is updated when loading user data.
3994 verifyLockTaskState(UserHandle.USER_SYSTEM);
3995
3996 final int flags = DevicePolicyManager.LOCK_TASK_FEATURE_NOTIFICATIONS
3997 | DevicePolicyManager.LOCK_TASK_FEATURE_OVERVIEW;
3998 assertExpectException(IllegalArgumentException.class,
3999 "Cannot use LOCK_TASK_FEATURE_OVERVIEW without LOCK_TASK_FEATURE_HOME",
4000 () -> dpm.setLockTaskFeatures(admin1, flags));
4001 }
4002
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01004003 public void testIsDeviceManaged() throws Exception {
4004 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4005 setupDeviceOwner();
4006
4007 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
4008 // find out that the device has a device owner.
4009 assertTrue(dpm.isDeviceManaged());
4010 mContext.binder.callingUid = 1234567;
4011 mContext.callerPermissions.add(permission.MANAGE_USERS);
4012 assertTrue(dpm.isDeviceManaged());
4013 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4014 mContext.binder.clearCallingIdentity();
4015 assertTrue(dpm.isDeviceManaged());
4016
4017 clearDeviceOwner();
4018
4019 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
4020 // not have a device owner.
4021 mContext.binder.callingUid = 1234567;
4022 mContext.callerPermissions.add(permission.MANAGE_USERS);
4023 assertFalse(dpm.isDeviceManaged());
4024 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4025 mContext.binder.clearCallingIdentity();
4026 assertFalse(dpm.isDeviceManaged());
4027 }
4028
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01004029 public void testDeviceOwnerOrganizationName() throws Exception {
4030 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4031 setupDeviceOwner();
4032
4033 dpm.setOrganizationName(admin1, "organization");
4034
4035 // Device owner can retrieve organization managing the device.
4036 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4037
4038 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
4039 mContext.binder.callingUid = 1234567;
4040 mContext.callerPermissions.add(permission.MANAGE_USERS);
4041 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4042 mContext.callerPermissions.remove(permission.MANAGE_USERS);
4043
4044 // System can retrieve organization managing the device.
4045 mContext.binder.clearCallingIdentity();
4046 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
4047
4048 // Removing the device owner clears the organization managing the device.
4049 clearDeviceOwner();
4050 assertNull(dpm.getDeviceOwnerOrganizationName());
4051 }
4052
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004053 public void testWipeDataManagedProfile() throws Exception {
4054 final int MANAGED_PROFILE_USER_ID = 15;
4055 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4056 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4057 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4058
4059 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004060 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004061 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
yuemingwf7f67dc2017-09-08 14:23:53 +01004062 // Get mock reason string since we throw an IAE with empty string input.
4063 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4064 thenReturn("Just a test string.");
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004065
4066 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004067 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004068 MANAGED_PROFILE_USER_ID);
4069 }
4070
4071 public void testWipeDataManagedProfileDisallowed() throws Exception {
4072 final int MANAGED_PROFILE_USER_ID = 15;
4073 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4074 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4075
4076 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004077 when(getServices().iactivityManager.getCurrentUser())
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004078 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4079
Pavel Grafov75c0a892017-05-18 17:28:27 +01004080 when(getServices().userManager.getUserRestrictionSource(
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004081 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4082 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4083 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004084 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4085 thenReturn("Just a test string.");
4086
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004087 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004088 // The PO is not allowed to remove the profile if the user restriction was set on the
4089 // profile by the system
4090 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4091 () -> dpm.wipeData(0));
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00004092 }
4093
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004094 public void testWipeDataDeviceOwner() throws Exception {
4095 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004096 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004097 UserManager.DISALLOW_FACTORY_RESET,
4098 UserHandle.SYSTEM))
4099 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004100 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4101 thenReturn("Just a test string.");
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004102
4103 dpm.wipeData(0);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004104 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004105 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4106 /*wipeEuicc=*/ eq(false));
4107 }
4108
4109 public void testWipeEuiccDataEnabled() throws Exception {
4110 setDeviceOwner();
4111 when(getServices().userManager.getUserRestrictionSource(
4112 UserManager.DISALLOW_FACTORY_RESET,
4113 UserHandle.SYSTEM))
4114 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
yuemingwf7f67dc2017-09-08 14:23:53 +01004115 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4116 thenReturn("Just a test string.");
yinxuf4f9cec2017-06-19 10:28:19 -07004117
4118 dpm.wipeData(WIPE_EUICC);
4119 verify(getServices().recoverySystem).rebootWipeUserData(
4120 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4121 /*wipeEuicc=*/ eq(true));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004122 }
4123
4124 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
4125 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004126 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004127 UserManager.DISALLOW_FACTORY_RESET,
4128 UserHandle.SYSTEM))
4129 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
yuemingwf7f67dc2017-09-08 14:23:53 +01004130 when(mContext.getResources().getString(R.string.work_profile_deleted_description_dpm_wipe)).
4131 thenReturn("Just a test string.");
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004132 // The DO is not allowed to wipe the device if the user restriction was set
4133 // by the system
4134 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4135 () -> dpm.wipeData(0));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004136 }
4137
4138 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
4139 final int MANAGED_PROFILE_USER_ID = 15;
4140 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4141 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4142
4143 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004144 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004145 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4146
Pavel Grafov75c0a892017-05-18 17:28:27 +01004147 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004148 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4149 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4150 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
4151
4152 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4153 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4154
4155 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4156 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4157 // Failed password attempts on the parent user are taken into account, as there isn't a
4158 // separate work challenge.
4159 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4160 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4161 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4162
4163 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
4164 // both the user restriction and the policy were set by the PO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004165 verify(getServices().userManagerInternal).removeUserEvenWhenDisallowed(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004166 MANAGED_PROFILE_USER_ID);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004167 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004168 }
4169
4170 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
4171 throws Exception {
4172 final int MANAGED_PROFILE_USER_ID = 15;
4173 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4174 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4175
4176 // Even if the caller is the managed profile, the current user is the user 0
Pavel Grafov75c0a892017-05-18 17:28:27 +01004177 when(getServices().iactivityManager.getCurrentUser())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004178 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
4179
Pavel Grafov75c0a892017-05-18 17:28:27 +01004180 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004181 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
4182 UserHandle.of(MANAGED_PROFILE_USER_ID)))
4183 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4184
4185 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4186 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4187
4188 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4189 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4190 // Failed password attempts on the parent user are taken into account, as there isn't a
4191 // separate work challenge.
4192 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4193 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4194 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4195
4196 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
4197 // not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004198 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004199 .removeUserEvenWhenDisallowed(anyInt());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004200 verifyZeroInteractions(getServices().recoverySystem);
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004201 }
4202
4203 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
4204 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004205 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004206 UserManager.DISALLOW_FACTORY_RESET,
4207 UserHandle.SYSTEM))
4208 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
4209
4210 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4211
4212 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4213 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4214 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4215 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4216 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4217
4218 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
4219 // user restriction and the policy were set by the DO.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004220 verify(getServices().recoverySystem).rebootWipeUserData(
yinxuf4f9cec2017-06-19 10:28:19 -07004221 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true),
4222 /*wipeEuicc=*/ eq(false));
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004223 }
4224
4225 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
4226 setDeviceOwner();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004227 when(getServices().userManager.getUserRestrictionSource(
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004228 UserManager.DISALLOW_FACTORY_RESET,
4229 UserHandle.SYSTEM))
4230 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
4231
4232 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
4233
4234 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4235 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
4236 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4237 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4238 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
4239
4240 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004241 verifyZeroInteractions(getServices().recoverySystem);
4242 verify(getServices().userManagerInternal, never())
Esteban Talaverab88f42b2017-01-24 16:47:16 +00004243 .removeUserEvenWhenDisallowed(anyInt());
4244 }
4245
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004246 public void testGetPermissionGrantState() throws Exception {
4247 final String permission = "some.permission";
4248 final String app1 = "com.example.app1";
4249 final String app2 = "com.example.app2";
4250
Pavel Grafov75c0a892017-05-18 17:28:27 +01004251 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004252 .thenReturn(PackageManager.PERMISSION_GRANTED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004253 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(getServices().packageManager)
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004254 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004255 when(getServices().packageManager.getPermissionFlags(permission, app1,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004256 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
4257 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004258 when(getServices().ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004259 .thenReturn(PackageManager.PERMISSION_DENIED);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004260 doReturn(0).when(getServices().packageManager).getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004261 UserHandle.SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004262 when(getServices().packageManager.getPermissionFlags(permission, app2,
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004263 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
4264
4265 // System can retrieve permission grant state.
4266 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004267 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004268 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4269 dpm.getPermissionGrantState(null, app1, permission));
4270 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4271 dpm.getPermissionGrantState(null, app2, permission));
4272
4273 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004274 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
4275 mContext.packageName = app1;
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004276 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4277 () -> dpm.getPermissionGrantState(null, app1, permission));
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004278
4279 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01004280 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4281 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01004282 setAsProfileOwner(admin1);
4283 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
4284 dpm.getPermissionGrantState(admin1, app1, permission));
4285 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
4286 dpm.getPermissionGrantState(admin1, app2, permission));
4287 }
4288
Rubin Xuaab7a412016-12-30 21:13:29 +00004289 public void testResetPasswordWithToken() throws Exception {
4290 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4291 setupDeviceOwner();
4292 // test token validation
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004293 assertExpectException(IllegalArgumentException.class, /* messageRegex= */ null,
4294 () -> dpm.setResetPasswordToken(admin1, new byte[31]));
4295
Rubin Xuaab7a412016-12-30 21:13:29 +00004296 // test adding a token
4297 final byte[] token = new byte[32];
4298 final long handle = 123456;
4299 final String password = "password";
Ram Periathiruvadi32d53552019-02-19 13:25:46 -08004300 when(getServices().lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM),
4301 nullable(EscrowTokenStateChangeCallback.class)))
4302 .thenReturn(handle);
Rubin Xuaab7a412016-12-30 21:13:29 +00004303 assertTrue(dpm.setResetPasswordToken(admin1, token));
4304
4305 // test password activation
Pavel Grafov75c0a892017-05-18 17:28:27 +01004306 when(getServices().lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004307 .thenReturn(true);
4308 assertTrue(dpm.isResetPasswordTokenActive(admin1));
4309
4310 // test reset password with token
Rubin Xua58125d2019-09-06 20:11:48 +01004311 when(getServices().lockPatternUtils.setLockCredentialWithToken(
4312 eq(LockscreenCredential.createPassword(password)),
4313 eq(handle), eq(token),
Rubin Xuaab7a412016-12-30 21:13:29 +00004314 eq(UserHandle.USER_SYSTEM)))
4315 .thenReturn(true);
4316 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
4317
4318 // test removing a token
Pavel Grafov75c0a892017-05-18 17:28:27 +01004319 when(getServices().lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
Rubin Xuaab7a412016-12-30 21:13:29 +00004320 .thenReturn(true);
4321 assertTrue(dpm.clearResetPasswordToken(admin1));
4322 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004323
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004324 public void testIsActivePasswordSufficient() throws Exception {
4325 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4326 mContext.packageName = admin1.getPackageName();
4327 setupDeviceOwner();
4328
4329 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
4330 dpm.setPasswordMinimumLength(admin1, 8);
4331 dpm.setPasswordMinimumLetters(admin1, 6);
4332 dpm.setPasswordMinimumLowerCase(admin1, 3);
4333 dpm.setPasswordMinimumUpperCase(admin1, 1);
4334 dpm.setPasswordMinimumNonLetter(admin1, 1);
4335 dpm.setPasswordMinimumNumeric(admin1, 1);
4336 dpm.setPasswordMinimumSymbols(admin1, 0);
4337
Rubin Xucc391c22018-01-02 20:37:35 +00004338 reset(mContext.spiedContext);
4339
Pavel Grafov6f334842019-08-06 14:37:06 +01004340 PasswordMetrics passwordMetricsNoSymbols = computeForPassword("abcdXYZ5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004341
4342 setActivePasswordState(passwordMetricsNoSymbols);
4343 assertTrue(dpm.isActivePasswordSufficient());
4344
4345 initializeDpms();
4346 reset(mContext.spiedContext);
4347 assertTrue(dpm.isActivePasswordSufficient());
4348
4349 // This call simulates the user entering the password for the first time after a reboot.
4350 // This causes password metrics to be reloaded into memory. Until this happens,
4351 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
4352 // even if the DPC changes password requirements so that the password no longer meets the
4353 // requirements. This is a known limitation of the current implementation of
4354 // isActivePasswordSufficient() - see b/34218769.
4355 setActivePasswordState(passwordMetricsNoSymbols);
4356 assertTrue(dpm.isActivePasswordSufficient());
4357
4358 dpm.setPasswordMinimumSymbols(admin1, 1);
4359 // This assertion would fail if we had not called setActivePasswordState() again after
4360 // initializeDpms() - see previous comment.
4361 assertFalse(dpm.isActivePasswordSufficient());
4362
4363 initializeDpms();
4364 reset(mContext.spiedContext);
4365 assertFalse(dpm.isActivePasswordSufficient());
4366
Pavel Grafov6f334842019-08-06 14:37:06 +01004367 PasswordMetrics passwordMetricsWithSymbols = computeForPassword("abcd.XY5".getBytes());
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004368
4369 setActivePasswordState(passwordMetricsWithSymbols);
4370 assertTrue(dpm.isActivePasswordSufficient());
4371 }
4372
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004373 public void testIsActivePasswordSufficient_noLockScreen() throws Exception {
4374 // If there is no lock screen, the password is considered empty no matter what, because
4375 // it provides no security.
4376 when(getServices().lockPatternUtils.hasSecureLockScreen()).thenReturn(false);
4377
4378 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4379 mContext.packageName = admin1.getPackageName();
4380 setupDeviceOwner();
Rubin Xu19854862019-08-15 16:37:23 +01004381 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
4382 // When there is no lockscreen, user password metrics is always empty.
4383 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
Pavel Grafov6f334842019-08-06 14:37:06 +01004384 .thenReturn(new PasswordMetrics(CREDENTIAL_TYPE_NONE));
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004385
4386 // If no password requirements are set, isActivePasswordSufficient should succeed.
4387 assertTrue(dpm.isActivePasswordSufficient());
4388
4389 // Now set some password quality requirements.
4390 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);
4391
4392 reset(mContext.spiedContext);
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004393 // This should be ignored, as there is no lock screen.
Lenka Trochtova66c492a2018-12-06 11:29:21 +01004394 dpm.reportPasswordChanged(userHandle);
4395
4396 // No broadcast should be sent.
4397 verify(mContext.spiedContext, times(0)).sendBroadcastAsUser(
4398 MockUtils.checkIntentAction(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED),
4399 MockUtils.checkUserHandle(userHandle));
4400
4401 // The active (nonexistent) password doesn't comply with the requirements.
4402 assertFalse(dpm.isActivePasswordSufficient());
4403 }
4404
Pavel Grafov75c0a892017-05-18 17:28:27 +01004405 private void setActivePasswordState(PasswordMetrics passwordMetrics)
4406 throws Exception {
4407 final int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004408 final long ident = mContext.binder.clearCallingIdentity();
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004409
Rubin Xu19854862019-08-15 16:37:23 +01004410 when(getServices().lockSettingsInternal.getUserPasswordMetrics(userHandle))
4411 .thenReturn(passwordMetrics);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004412 dpm.reportPasswordChanged(userHandle);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004413
Rubin Xucc391c22018-01-02 20:37:35 +00004414 // Drain ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED broadcasts as part of
4415 // reportPasswordChanged()
Rubin Xu19854862019-08-15 16:37:23 +01004416 // This broadcast should be sent 2-4 times:
Eran Messeri9ecde422018-04-30 16:16:39 +01004417 // * Twice from calls to DevicePolicyManagerService.updatePasswordExpirationsLocked,
4418 // once for each affected user, in DevicePolicyManagerService.reportPasswordChanged.
Rubin Xu19854862019-08-15 16:37:23 +01004419 // * Optionally, at most twice from calls to DevicePolicyManagerService.saveSettingsLocked
Eran Messeri9ecde422018-04-30 16:16:39 +01004420 // in DevicePolicyManagerService.reportPasswordChanged, once with the userId
4421 // the password change is relevant to and another with the credential owner of said
Rubin Xu19854862019-08-15 16:37:23 +01004422 // userId, if the password checkpoint value changes.
4423 verify(mContext.spiedContext, atMost(4)).sendBroadcastAsUser(
4424 MockUtils.checkIntentAction(
4425 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4426 MockUtils.checkUserHandle(userHandle));
4427 verify(mContext.spiedContext, atLeast(2)).sendBroadcastAsUser(
Rubin Xucc391c22018-01-02 20:37:35 +00004428 MockUtils.checkIntentAction(
4429 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
4430 MockUtils.checkUserHandle(userHandle));
4431
Pavel Grafov75c0a892017-05-18 17:28:27 +01004432 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
4433 intent.setComponent(admin1);
Rubin Xucc391c22018-01-02 20:37:35 +00004434 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userHandle));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004435
4436 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4437 MockUtils.checkIntent(intent),
Jonathan Scott367ebf42019-05-16 15:13:17 +01004438 MockUtils.checkUserHandle(userHandle),
4439 eq(null),
4440 any());
Pavel Grafov75c0a892017-05-18 17:28:27 +01004441
4442 // CertificateMonitor.updateInstalledCertificates is called on the background thread,
4443 // let it finish with system uid, otherwise it will throw and crash.
4444 flushTasks();
4445
4446 mContext.binder.restoreCallingIdentity(ident);
Eric Sandnessfabfcb02017-05-03 18:28:56 +01004447 }
4448
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004449 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
4450 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4451 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4452 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4453 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4454 DpmMockContext.SYSTEM_UID);
4455 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4456 DpmMockContext.SYSTEM_UID);
4457
4458 // Set up a device owner.
4459 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004460 setupDeviceOwner();
4461
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004462 // First and second user set IMEs manually.
4463 mContext.binder.callingUid = firstUserSystemUid;
4464 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4465 mContext.binder.callingUid = secondUserSystemUid;
4466 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004467
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004468 // Device owner changes IME for first user.
4469 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004470 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004471 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004472 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004473 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004474 UserHandle.USER_SYSTEM);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004475 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004476 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4477 mContext.binder.callingUid = firstUserSystemUid;
4478 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4479 mContext.binder.callingUid = secondUserSystemUid;
4480 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004481
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004482 // Second user changes IME manually.
4483 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4484 mContext.binder.callingUid = firstUserSystemUid;
4485 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4486 mContext.binder.callingUid = secondUserSystemUid;
4487 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004488
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004489 // First user changes IME manually.
4490 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4491 mContext.binder.callingUid = firstUserSystemUid;
4492 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4493 mContext.binder.callingUid = secondUserSystemUid;
4494 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004495
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004496 // Device owner changes IME for first user again.
4497 mContext.binder.callingUid = deviceOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004498 when(getServices().settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004499 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004500 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004501 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004502 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004503 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4504 mContext.binder.callingUid = firstUserSystemUid;
4505 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4506 mContext.binder.callingUid = secondUserSystemUid;
4507 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004508
4509 // Restarting the DPMS should not lose information.
4510 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004511 mContext.binder.callingUid = firstUserSystemUid;
4512 assertTrue(dpm.isCurrentInputMethodSetByOwner());
4513 mContext.binder.callingUid = secondUserSystemUid;
4514 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004515
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004516 // Device owner can find out whether it set the current IME itself.
4517 mContext.binder.callingUid = deviceOwnerUid;
4518 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004519
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004520 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004521 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004522 mContext.binder.callingUid = firstUserSystemUid;
4523 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4524 mContext.binder.callingUid = secondUserSystemUid;
4525 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004526 }
4527
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004528 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
4529 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
4530 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
4531 final int profileOwnerUid = DpmMockContext.CALLER_UID;
4532 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
4533 DpmMockContext.SYSTEM_UID);
4534 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4535 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004536
4537 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004538 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004539 setupProfileOwner();
4540
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004541 // First and second user set IMEs manually.
4542 mContext.binder.callingUid = firstUserSystemUid;
4543 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4544 mContext.binder.callingUid = secondUserSystemUid;
4545 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004546
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004547 // Profile owner changes IME for second user.
4548 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004549 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004550 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004551 dpm.setSecureSetting(admin1, currentIme, "ime2");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004552 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004553 DpmMockContext.CALLER_USER_HANDLE);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004554 reset(getServices().settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004555 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4556 mContext.binder.callingUid = firstUserSystemUid;
4557 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4558 mContext.binder.callingUid = secondUserSystemUid;
4559 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004560
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004561 // First user changes IME manually.
4562 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4563 mContext.binder.callingUid = firstUserSystemUid;
4564 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4565 mContext.binder.callingUid = secondUserSystemUid;
4566 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004567
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004568 // Second user changes IME manually.
4569 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4570 mContext.binder.callingUid = firstUserSystemUid;
4571 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4572 mContext.binder.callingUid = secondUserSystemUid;
4573 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004574
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004575 // Profile owner changes IME for second user again.
4576 mContext.binder.callingUid = profileOwnerUid;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004577 when(getServices().settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004578 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004579 dpm.setSecureSetting(admin1, currentIme, "ime3");
Pavel Grafov75c0a892017-05-18 17:28:27 +01004580 verify(getServices().settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004581 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004582 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4583 mContext.binder.callingUid = firstUserSystemUid;
4584 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4585 mContext.binder.callingUid = secondUserSystemUid;
4586 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004587
4588 // Restarting the DPMS should not lose information.
4589 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004590 mContext.binder.callingUid = firstUserSystemUid;
4591 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4592 mContext.binder.callingUid = secondUserSystemUid;
4593 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004594
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004595 // Profile owner can find out whether it set the current IME itself.
4596 mContext.binder.callingUid = profileOwnerUid;
4597 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004598
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004599 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004600 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004601 mContext.binder.callingUid = firstUserSystemUid;
4602 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4603 mContext.binder.callingUid = secondUserSystemUid;
4604 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004605 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004606
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004607 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4608 throws Exception {
4609 // Set up a device owner.
4610 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4611 setupDeviceOwner();
4612 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4613 }
4614
4615 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4616 throws Exception {
4617 // Set up a profile owner.
4618 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4619 setupProfileOwner();
4620 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4621 }
4622
4623 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4624 int adminUid) throws Exception {
4625 mContext.binder.callingUid = adminUid;
4626 final int userId = UserHandle.getUserId(adminUid);
4627
4628 final String packageName = "some.package";
4629 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4630 admin1, Collections.singletonList(packageName)));
4631 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4632
4633 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4634 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4635
4636 // Attempt to set to empty list (which means no listener is whitelisted)
4637 mContext.binder.callingUid = adminUid;
4638 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004639 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004640 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4641
4642 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4643 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4644 }
4645
4646 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4647 // Set up a managed profile
4648 final int MANAGED_PROFILE_USER_ID = 15;
4649 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4650 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4651 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4652
4653 final String permittedListener = "some.package";
4654 setupPackageInPackageManager(
4655 permittedListener,
4656 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4657 /*appId=*/ 12345, /*flags=*/ 0);
4658
4659 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4660 admin1, Collections.singletonList(permittedListener)));
4661
Pavel Grafova1ea8d92017-05-25 21:55:24 +01004662 // isNotificationListenerServicePermitted should throw if not called from System.
4663 assertExpectException(SecurityException.class, /* messageRegex= */ null,
4664 () -> dpms.isNotificationListenerServicePermitted(
4665 permittedListener, MANAGED_PROFILE_USER_ID));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004666
4667 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4668 assertTrue(dpms.isNotificationListenerServicePermitted(
4669 permittedListener, MANAGED_PROFILE_USER_ID));
4670 }
4671
4672 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4673 throws Exception {
4674 // Set up a managed profile
4675 final int MANAGED_PROFILE_USER_ID = 15;
4676 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4677 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4678 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4679
4680 final String permittedListener = "permitted.package";
4681 int appId = 12345;
4682 setupPackageInPackageManager(
4683 permittedListener,
4684 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4685 appId, /*flags=*/ 0);
4686
4687 final String notPermittedListener = "not.permitted.package";
4688 setupPackageInPackageManager(
4689 notPermittedListener,
4690 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4691 ++appId, /*flags=*/ 0);
4692
4693 final String systemListener = "system.package";
4694 setupPackageInPackageManager(
4695 systemListener,
4696 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4697 ++appId, ApplicationInfo.FLAG_SYSTEM);
4698
4699 // By default all packages are allowed
4700 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4701
4702 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4703 assertTrue(dpms.isNotificationListenerServicePermitted(
4704 permittedListener, MANAGED_PROFILE_USER_ID));
4705 assertTrue(dpms.isNotificationListenerServicePermitted(
4706 notPermittedListener, MANAGED_PROFILE_USER_ID));
4707 assertTrue(dpms.isNotificationListenerServicePermitted(
4708 systemListener, MANAGED_PROFILE_USER_ID));
4709
4710 // Setting only one package in the whitelist
4711 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4712 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4713 admin1, Collections.singletonList(permittedListener)));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004714 final List<String> permittedListeners =
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004715 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4716 assertEquals(1, permittedListeners.size());
4717 assertEquals(permittedListener, permittedListeners.get(0));
4718
4719 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4720 assertTrue(dpms.isNotificationListenerServicePermitted(
4721 permittedListener, MANAGED_PROFILE_USER_ID));
4722 assertFalse(dpms.isNotificationListenerServicePermitted(
4723 notPermittedListener, MANAGED_PROFILE_USER_ID));
4724 // System packages are always allowed (even if not in the whitelist)
4725 assertTrue(dpms.isNotificationListenerServicePermitted(
4726 systemListener, MANAGED_PROFILE_USER_ID));
4727
4728 // Setting an empty whitelist - only system listeners allowed
4729 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4730 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004731 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004732 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4733
4734 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4735 assertFalse(dpms.isNotificationListenerServicePermitted(
4736 permittedListener, MANAGED_PROFILE_USER_ID));
4737 assertFalse(dpms.isNotificationListenerServicePermitted(
4738 notPermittedListener, MANAGED_PROFILE_USER_ID));
4739 // System packages are always allowed (even if not in the whitelist)
4740 assertTrue(dpms.isNotificationListenerServicePermitted(
4741 systemListener, MANAGED_PROFILE_USER_ID));
4742
4743 // Setting a null whitelist - all listeners allowed
4744 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4745 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4746 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4747
4748 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4749 assertTrue(dpms.isNotificationListenerServicePermitted(
4750 permittedListener, MANAGED_PROFILE_USER_ID));
4751 assertTrue(dpms.isNotificationListenerServicePermitted(
4752 notPermittedListener, MANAGED_PROFILE_USER_ID));
4753 assertTrue(dpms.isNotificationListenerServicePermitted(
4754 systemListener, MANAGED_PROFILE_USER_ID));
4755 }
4756
4757 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4758 throws Exception {
4759 // Set up a managed profile
4760 final int MANAGED_PROFILE_USER_ID = 15;
4761 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4762 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4763 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4764
4765 final String nonSystemPackage = "non.system.package";
4766 int appId = 12345;
4767 setupPackageInPackageManager(
4768 nonSystemPackage,
4769 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4770 appId, /*flags=*/ 0);
4771
4772 final String systemListener = "system.package";
4773 setupPackageInPackageManager(
4774 systemListener,
4775 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4776 ++appId, ApplicationInfo.FLAG_SYSTEM);
4777
4778 // By default all packages are allowed (for all profiles)
4779 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4780
4781 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4782 assertTrue(dpms.isNotificationListenerServicePermitted(
4783 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4784 assertTrue(dpms.isNotificationListenerServicePermitted(
4785 systemListener, MANAGED_PROFILE_USER_ID));
4786 assertTrue(dpms.isNotificationListenerServicePermitted(
4787 nonSystemPackage, UserHandle.USER_SYSTEM));
4788 assertTrue(dpms.isNotificationListenerServicePermitted(
4789 systemListener, UserHandle.USER_SYSTEM));
4790
4791 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4792 // all allowed in primary profile
4793 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4794 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
Pavel Grafov75c0a892017-05-18 17:28:27 +01004795 admin1, Collections.emptyList()));
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004796 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4797
4798 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4799 assertFalse(dpms.isNotificationListenerServicePermitted(
4800 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4801 assertTrue(dpms.isNotificationListenerServicePermitted(
4802 systemListener, MANAGED_PROFILE_USER_ID));
4803 assertTrue(dpms.isNotificationListenerServicePermitted(
4804 nonSystemPackage, UserHandle.USER_SYSTEM));
4805 assertTrue(dpms.isNotificationListenerServicePermitted(
4806 systemListener, UserHandle.USER_SYSTEM));
4807 }
4808
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004809 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004810 mServiceContext.packageName = mRealTestContext.getPackageName();
4811 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4812 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004813 setDeviceOwner();
4814
Pavel Grafov75c0a892017-05-18 17:28:27 +01004815 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004816 }
4817
4818 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004819 mServiceContext.packageName = mRealTestContext.getPackageName();
4820 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4821 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004822 setAsProfileOwner(admin1);
4823
Pavel Grafov75c0a892017-05-18 17:28:27 +01004824 verifyCanGetOwnerInstalledCaCerts(admin1, mAdmin1Context);
4825 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, mAdmin1Context);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004826 }
4827
4828 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004829 mServiceContext.packageName = mRealTestContext.getPackageName();
4830 mServiceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4831 mAdmin1Context.binder.callingUid = DpmMockContext.CALLER_UID;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004832 setAsProfileOwner(admin1);
4833
Pavel Grafov75c0a892017-05-18 17:28:27 +01004834 final DpmMockContext caller = new DpmMockContext(getServices(), mRealTestContext);
4835 caller.packageName = "com.example.delegate";
4836 caller.binder.callingUid = setupPackageInPackageManager(caller.packageName,
4837 DpmMockContext.CALLER_USER_HANDLE, 20988, ApplicationInfo.FLAG_HAS_CODE);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004838
Pavel Grafov75c0a892017-05-18 17:28:27 +01004839 // Make caller a delegated cert installer.
4840 runAsCaller(mAdmin1Context, dpms,
4841 dpm -> dpm.setCertInstallerPackage(admin1, caller.packageName));
Robin Lee2c68dad2017-03-17 12:50:24 +00004842
4843 verifyCanGetOwnerInstalledCaCerts(null, caller);
4844 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004845 }
4846
Rubin Xucc391c22018-01-02 20:37:35 +00004847 public void testDisallowSharingIntoProfileSetRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004848 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4849 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004850 Bundle restriction = new Bundle();
4851 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4852
4853 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4854 RestrictionsListener listener = new RestrictionsListener(mContext);
4855 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, restriction,
4856 new Bundle());
4857 verifyDataSharingChangedBroadcast();
4858 }
4859
4860 public void testDisallowSharingIntoProfileClearRestriction() {
Rubin Xu255cb7712018-03-02 16:56:09 +00004861 when(mServiceContext.resources.getString(R.string.config_managed_provisioning_package))
4862 .thenReturn("com.android.managedprovisioning");
Rubin Xucc391c22018-01-02 20:37:35 +00004863 Bundle restriction = new Bundle();
4864 restriction.putBoolean(UserManager.DISALLOW_SHARE_INTO_MANAGED_PROFILE, true);
4865
4866 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4867 RestrictionsListener listener = new RestrictionsListener(mContext);
4868 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4869 restriction);
4870 verifyDataSharingChangedBroadcast();
4871 }
4872
4873 public void testDisallowSharingIntoProfileUnchanged() {
4874 RestrictionsListener listener = new RestrictionsListener(mContext);
4875 listener.onUserRestrictionsChanged(DpmMockContext.CALLER_USER_HANDLE, new Bundle(),
4876 new Bundle());
4877 verify(mContext.spiedContext, never()).sendBroadcastAsUser(any(), any());
4878 }
4879
4880 private void verifyDataSharingChangedBroadcast() {
4881 Intent expectedIntent = new Intent(
4882 DevicePolicyManager.ACTION_DATA_SHARING_RESTRICTION_CHANGED);
4883 expectedIntent.setPackage("com.android.managedprovisioning");
4884 expectedIntent.putExtra(Intent.EXTRA_USER_ID, DpmMockContext.CALLER_USER_HANDLE);
4885 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
4886 MockUtils.checkIntent(expectedIntent),
4887 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
4888 }
4889
yuemingwe3d9c092018-01-11 12:11:44 +00004890 public void testOverrideApnAPIsFailWithPO() throws Exception {
4891 setupProfileOwner();
yuemingw7e1298f2018-03-01 14:42:57 +00004892 ApnSetting apn = (new ApnSetting.Builder())
4893 .setApnName("test")
4894 .setEntryName("test")
4895 .setApnTypeBitmask(ApnSetting.TYPE_DEFAULT)
4896 .build();
yuemingwe3d9c092018-01-11 12:11:44 +00004897 assertExpectException(SecurityException.class, null, () ->
4898 dpm.addOverrideApn(admin1, apn));
4899 assertExpectException(SecurityException.class, null, () ->
4900 dpm.updateOverrideApn(admin1, 0, apn));
4901 assertExpectException(SecurityException.class, null, () ->
4902 dpm.removeOverrideApn(admin1, 0));
4903 assertExpectException(SecurityException.class, null, () ->
4904 dpm.getOverrideApns(admin1));
4905 assertExpectException(SecurityException.class, null, () ->
4906 dpm.setOverrideApnsEnabled(admin1, false));
4907 assertExpectException(SecurityException.class, null, () ->
4908 dpm.isOverrideApnEnabled(admin1));
4909 }
4910
Robin Lee2c68dad2017-03-17 12:50:24 +00004911 private void verifyCanGetOwnerInstalledCaCerts(
4912 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004913 final String alias = "cert";
4914 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004915
4916 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004917 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004918 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4919 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004920 }
4921 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4922
4923 // caller: device admin or delegated certificate installer
4924 callerContext.applicationInfo = new ApplicationInfo();
4925 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4926
4927 // system_server
4928 final DpmMockContext serviceContext = mContext;
4929 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01004930 getServices().addPackageContext(callerUser, admin1Context);
4931 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00004932
4933 // Install a CA cert.
4934 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01004935 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00004936 .thenReturn(alias);
4937 assertTrue(dpm.installCaCert(caller, caCert));
Pavel Grafov75c0a892017-05-18 17:28:27 +01004938 when(getServices().keyChainConnection.getService().getUserCaAliases())
Robin Lee2c68dad2017-03-17 12:50:24 +00004939 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004940 });
4941
Pavel Grafov75c0a892017-05-18 17:28:27 +01004942 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4943 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4944 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004945 flushTasks();
4946
Robin Lee2c68dad2017-03-17 12:50:24 +00004947 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4948
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004949 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004950 runAsCaller(admin1Context, dpms, (dpm) -> {
4951 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
Pavel Grafov75c0a892017-05-18 17:28:27 +01004952 assertEquals(Collections.singletonList(alias), installedCaCerts);
Robin Lee2c68dad2017-03-17 12:50:24 +00004953 ownerInstalledCaCerts.addAll(installedCaCerts);
4954 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004955
4956 // Restarting the DPMS should not lose information.
4957 initializeDpms();
Pavel Grafov75c0a892017-05-18 17:28:27 +01004958 runAsCaller(admin1Context, dpms, (dpm) ->
4959 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser)));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004960
4961 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004962 runAsCaller(serviceContext, dpms, (dpm) -> {
4963 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004964
Robin Lee2c68dad2017-03-17 12:50:24 +00004965 // Remove the CA cert.
Pavel Grafov75c0a892017-05-18 17:28:27 +01004966 reset(getServices().keyChainConnection.getService());
Robin Lee2c68dad2017-03-17 12:50:24 +00004967 });
4968
Pavel Grafov75c0a892017-05-18 17:28:27 +01004969 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4970 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
4971 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004972 flushTasks();
4973
4974 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4975 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004976 runAsCaller(admin1Context, dpms, (dpm) -> {
4977 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4978 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004979 }
4980
Robin Lee2c68dad2017-03-17 12:50:24 +00004981 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4982 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004983 final String alias = "cert";
4984 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004985
4986 // device admin (used for posting the tls notification)
Pavel Grafov75c0a892017-05-18 17:28:27 +01004987 DpmMockContext admin1Context = mAdmin1Context;
Robin Lee2c68dad2017-03-17 12:50:24 +00004988 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4989 admin1Context = callerContext;
Robin Lee2c68dad2017-03-17 12:50:24 +00004990 }
4991 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4992
4993 // caller: device admin or delegated certificate installer
4994 callerContext.applicationInfo = new ApplicationInfo();
4995 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4996
4997 // system_server
4998 final DpmMockContext serviceContext = mContext;
4999 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Pavel Grafov75c0a892017-05-18 17:28:27 +01005000 getServices().addPackageContext(callerUser, admin1Context);
5001 getServices().addPackageContext(callerUser, callerContext);
Robin Lee2c68dad2017-03-17 12:50:24 +00005002
5003 // Install a CA cert as caller
5004 runAsCaller(callerContext, dpms, (dpm) -> {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005005 when(getServices().keyChainConnection.getService().installCaCertificate(caCert))
Robin Lee2c68dad2017-03-17 12:50:24 +00005006 .thenReturn(alias);
5007 assertTrue(dpm.installCaCert(callerName, caCert));
5008 });
5009
5010 // Fake the CA cert as having been installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005011 when(getServices().keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005012 .thenReturn(asSlice(new String[] {alias}));
Pavel Grafov75c0a892017-05-18 17:28:27 +01005013 getServices().injectBroadcast(mServiceContext, new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
5014 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()),
5015 callerUser.getIdentifier());
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005016 flushTasks();
5017
Robin Lee2c68dad2017-03-17 12:50:24 +00005018 // Removing the Profile Owner should clear the information on which CA certs were installed
Pavel Grafov75c0a892017-05-18 17:28:27 +01005019 runAsCaller(admin1Context, dpms, dpm -> dpm.clearProfileOwner(admin1));
Robin Lee2c68dad2017-03-17 12:50:24 +00005020
5021 runAsCaller(serviceContext, dpms, (dpm) -> {
5022 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
5023 assertNotNull(ownerInstalledCaCerts);
5024 assertTrue(ownerInstalledCaCerts.isEmpty());
5025 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005026 }
5027
Eran Messeri94d56762017-12-21 20:50:54 +00005028 private void assertAttestationFlags(int attestationFlags, int[] expectedFlags) {
5029 int[] gotFlags = DevicePolicyManagerService.translateIdAttestationFlags(attestationFlags);
5030 Arrays.sort(gotFlags);
5031 Arrays.sort(expectedFlags);
5032 assertTrue(Arrays.equals(expectedFlags, gotFlags));
5033 }
5034
5035 public void testTranslationOfIdAttestationFlag() {
5036 int[] allIdTypes = new int[]{ID_TYPE_SERIAL, ID_TYPE_IMEI, ID_TYPE_MEID};
5037 int[] correspondingAttUtilsTypes = new int[]{
5038 AttestationUtils.ID_TYPE_SERIAL, AttestationUtils.ID_TYPE_IMEI,
5039 AttestationUtils.ID_TYPE_MEID};
5040
5041 // Test translation of zero flags
5042 assertNull(DevicePolicyManagerService.translateIdAttestationFlags(0));
5043
5044 // Test translation of the ID_TYPE_BASE_INFO flag, which should yield an empty, but
5045 // non-null array
5046 assertAttestationFlags(ID_TYPE_BASE_INFO, new int[] {});
5047
5048 // Test translation of a single flag
5049 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_SERIAL,
5050 new int[] {AttestationUtils.ID_TYPE_SERIAL});
5051 assertAttestationFlags(ID_TYPE_SERIAL, new int[] {AttestationUtils.ID_TYPE_SERIAL});
5052
5053 // Test translation of two flags
5054 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI,
5055 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL});
5056 assertAttestationFlags(ID_TYPE_BASE_INFO | ID_TYPE_MEID | ID_TYPE_SERIAL,
5057 new int[] {AttestationUtils.ID_TYPE_MEID, AttestationUtils.ID_TYPE_SERIAL});
5058
5059 // Test translation of all three flags
5060 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID,
5061 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5062 AttestationUtils.ID_TYPE_MEID});
5063 // Test translation of all three flags
5064 assertAttestationFlags(ID_TYPE_SERIAL | ID_TYPE_IMEI | ID_TYPE_MEID | ID_TYPE_BASE_INFO,
5065 new int[] {AttestationUtils.ID_TYPE_IMEI, AttestationUtils.ID_TYPE_SERIAL,
5066 AttestationUtils.ID_TYPE_MEID});
5067 }
5068
arangelov08d534b2018-01-22 15:20:53 +00005069 public void testRevertDeviceOwnership_noMetadataFile() throws Exception {
5070 setDeviceOwner();
5071 initializeDpms();
5072 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5073 assertTrue(dpms.isDeviceOwner(admin1, UserHandle.USER_SYSTEM));
5074 assertTrue(dpms.isAdminActive(admin1, UserHandle.USER_SYSTEM));
5075 }
5076
5077 public void testRevertDeviceOwnership_adminAndDeviceMigrated() throws Exception {
5078 DpmTestUtils.writeInputStreamToFile(
5079 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5080 getDeviceOwnerPoliciesFile());
5081 DpmTestUtils.writeInputStreamToFile(
5082 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_migrated),
5083 getDeviceOwnerFile());
5084 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5085 }
5086
5087 public void testRevertDeviceOwnership_deviceNotMigrated()
5088 throws Exception {
5089 DpmTestUtils.writeInputStreamToFile(
5090 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5091 getDeviceOwnerPoliciesFile());
5092 DpmTestUtils.writeInputStreamToFile(
5093 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5094 getDeviceOwnerFile());
5095 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5096 }
5097
5098 public void testRevertDeviceOwnership_adminAndDeviceNotMigrated()
5099 throws Exception {
5100 DpmTestUtils.writeInputStreamToFile(
5101 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5102 getDeviceOwnerPoliciesFile());
5103 DpmTestUtils.writeInputStreamToFile(
5104 getRawStream(com.android.frameworks.servicestests.R.raw.device_owner_not_migrated),
5105 getDeviceOwnerFile());
5106 assertDeviceOwnershipRevertedWithFakeTransferMetadata();
5107 }
5108
5109 public void testRevertProfileOwnership_noMetadataFile() throws Exception {
5110 setupProfileOwner();
5111 initializeDpms();
5112 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5113 assertTrue(dpms.isProfileOwner(admin1, DpmMockContext.CALLER_USER_HANDLE));
5114 assertTrue(dpms.isAdminActive(admin1, DpmMockContext.CALLER_USER_HANDLE));
5115 UserHandle userHandle = UserHandle.of(DpmMockContext.CALLER_USER_HANDLE);
5116 }
5117
5118 public void testRevertProfileOwnership_adminAndProfileMigrated() throws Exception {
5119 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5120 UserHandle.USER_SYSTEM);
5121 DpmTestUtils.writeInputStreamToFile(
5122 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5123 getProfileOwnerPoliciesFile());
5124 DpmTestUtils.writeInputStreamToFile(
5125 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_migrated),
5126 getProfileOwnerFile());
5127 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5128 }
5129
5130 public void testRevertProfileOwnership_profileNotMigrated() throws Exception {
5131 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5132 UserHandle.USER_SYSTEM);
5133 DpmTestUtils.writeInputStreamToFile(
5134 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_migrated),
5135 getProfileOwnerPoliciesFile());
5136 DpmTestUtils.writeInputStreamToFile(
5137 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5138 getProfileOwnerFile());
5139 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5140 }
5141
5142 public void testRevertProfileOwnership_adminAndProfileNotMigrated() throws Exception {
5143 getServices().addUser(DpmMockContext.CALLER_USER_HANDLE, UserInfo.FLAG_MANAGED_PROFILE,
5144 UserHandle.USER_SYSTEM);
5145 DpmTestUtils.writeInputStreamToFile(
5146 getRawStream(com.android.frameworks.servicestests.R.raw.active_admin_not_migrated),
5147 getProfileOwnerPoliciesFile());
5148 DpmTestUtils.writeInputStreamToFile(
5149 getRawStream(com.android.frameworks.servicestests.R.raw.profile_owner_not_migrated),
5150 getProfileOwnerFile());
5151 assertProfileOwnershipRevertedWithFakeTransferMetadata();
5152 }
5153
Eran Messeribb271892018-10-17 18:27:50 +01005154 public void testGrantDeviceIdsAccess_notToProfileOwner() throws Exception {
5155 setupProfileOwner();
5156 configureContextForAccess(mContext, false);
5157
5158 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005159 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin2));
Eran Messeribb271892018-10-17 18:27:50 +01005160 }
5161
5162 public void testGrantDeviceIdsAccess_notByAuthorizedCaller() throws Exception {
5163 setupProfileOwner();
5164 configureContextForAccess(mContext, false);
5165
5166 assertExpectException(SecurityException.class, /* messageRegex= */ null,
Eran Messeri18d21312019-11-14 22:44:40 +00005167 () -> dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1));
Eran Messeribb271892018-10-17 18:27:50 +01005168 }
5169
5170 public void testGrantDeviceIdsAccess_byAuthorizedSystemCaller() throws Exception {
5171 setupProfileOwner();
5172
5173 // This method will throw if the system context could not call
Eran Messeri18d21312019-11-14 22:44:40 +00005174 // markProfileOwnerOfOrganizationOwnedDevice successfully.
5175 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005176 }
5177
Eran Messerib8c46e02019-11-07 12:06:18 +00005178 private void configureContextForAccess(DpmMockContext context, boolean granted) {
Eran Messeribb271892018-10-17 18:27:50 +01005179 when(context.spiedContext.checkCallingPermission(
Eran Messeri18d21312019-11-14 22:44:40 +00005180 permission.MARK_DEVICE_ORGANIZATION_OWNED))
Eran Messeribb271892018-10-17 18:27:50 +01005181 .thenReturn(granted ? PackageManager.PERMISSION_GRANTED
5182 : PackageManager.PERMISSION_DENIED);
Eran Messerib8c46e02019-11-07 12:06:18 +00005183
5184 when(getServices().userManager.getProfileParent(any()))
5185 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005186 }
5187
5188 public void testGrantDeviceIdsAccess_byAuthorizedManagedProvisioning() throws Exception {
5189 setupProfileOwner();
5190
5191 final long ident = mServiceContext.binder.clearCallingIdentity();
5192 configureContextForAccess(mServiceContext, true);
5193
5194 mServiceContext.binder.callingUid =
5195 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5196 DpmMockContext.CALLER_MANAGED_PROVISIONING_UID);
5197 try {
5198 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005199 dpm.markProfileOwnerOnOrganizationOwnedDevice(admin1);
Eran Messeribb271892018-10-17 18:27:50 +01005200 });
5201 } finally {
5202 mServiceContext.binder.restoreCallingIdentity(ident);
5203 }
5204 }
5205
5206 public void testEnforceCallerCanRequestDeviceIdAttestation_deviceOwnerCaller()
5207 throws Exception {
5208 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
5209 setupDeviceOwner();
5210 configureContextForAccess(mContext, false);
5211
5212 // Device owner should be allowed to request Device ID attestation.
5213 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5214 DpmMockContext.CALLER_SYSTEM_USER_UID);
5215
5216 // Another package must not be allowed to request Device ID attestation.
5217 assertExpectException(SecurityException.class, null,
5218 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5219 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5220 // Another component that is not the admin must not be allowed to request Device ID
5221 // attestation.
5222 assertExpectException(SecurityException.class, null,
5223 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5224 admin1.getPackageName(), DpmMockContext.CALLER_UID));
5225 }
5226
5227 public void testEnforceCallerCanRequestDeviceIdAttestation_profileOwnerCaller()
5228 throws Exception {
5229 configureContextForAccess(mContext, false);
5230
5231 // Make sure a security exception is thrown if the device has no profile owner.
5232 assertExpectException(SecurityException.class, null,
5233 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5234 admin1.getPackageName(), DpmMockContext.CALLER_SYSTEM_USER_UID));
5235
5236 setupProfileOwner();
Eran Messeri18d21312019-11-14 22:44:40 +00005237 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005238
5239 // The profile owner is allowed to request Device ID attestation.
5240 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5241 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5242 DpmMockContext.CALLER_UID);
5243 // But not another package.
5244 assertExpectException(SecurityException.class, null,
5245 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5246 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5247 // Or another component which is not the admin.
5248 assertExpectException(SecurityException.class, null,
5249 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin2,
5250 admin2.getPackageName(), DpmMockContext.CALLER_UID));
5251 }
5252
5253 public void runAsDelegatedCertInstaller(DpmRunnable action) throws Exception {
5254 final long ident = mServiceContext.binder.clearCallingIdentity();
5255
5256 mServiceContext.binder.callingUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5257 DpmMockContext.DELEGATE_CERT_INSTALLER_UID);
5258 try {
5259 runAsCaller(mServiceContext, dpms, action);
5260 } finally {
5261 mServiceContext.binder.restoreCallingIdentity(ident);
5262 }
5263 }
5264
5265 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCaller() throws Exception {
5266 setupProfileOwner();
5267 markDelegatedCertInstallerAsInstalled();
5268
5269 // Configure a delegated cert installer.
5270 runAsCaller(mServiceContext, dpms,
5271 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5272 Arrays.asList(DELEGATION_CERT_INSTALL)));
5273
Eran Messeri18d21312019-11-14 22:44:40 +00005274 configureProfileOwnerOfOrgOwnedDevice(admin1, DpmMockContext.CALLER_USER_HANDLE);
Eran Messeribb271892018-10-17 18:27:50 +01005275
5276 // Make sure that the profile owner can still request Device ID attestation.
5277 mServiceContext.binder.callingUid = DpmMockContext.CALLER_UID;
5278 dpms.enforceCallerCanRequestDeviceIdAttestation(admin1, admin1.getPackageName(),
5279 DpmMockContext.CALLER_UID);
5280
5281 runAsDelegatedCertInstaller(dpm -> {
5282 dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5283 DpmMockContext.DELEGATE_PACKAGE_NAME,
5284 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5285 DpmMockContext.DELEGATE_CERT_INSTALLER_UID));
5286 });
5287 }
5288
5289 public void testEnforceCallerCanRequestDeviceIdAttestation_delegateCallerWithoutPermissions()
5290 throws Exception {
5291 setupProfileOwner();
5292 markDelegatedCertInstallerAsInstalled();
5293
5294 // Configure a delegated cert installer.
5295 runAsCaller(mServiceContext, dpms,
5296 dpm -> dpm.setDelegatedScopes(admin1, DpmMockContext.DELEGATE_PACKAGE_NAME,
5297 Arrays.asList(DELEGATION_CERT_INSTALL)));
5298
5299
5300 assertExpectException(SecurityException.class, null,
5301 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(admin1,
5302 admin1.getPackageName(),
5303 DpmMockContext.CALLER_UID));
5304
5305 runAsDelegatedCertInstaller(dpm -> {
5306 assertExpectException(SecurityException.class, /* messageRegex= */ null,
5307 () -> dpms.enforceCallerCanRequestDeviceIdAttestation(null,
5308 DpmMockContext.DELEGATE_PACKAGE_NAME,
5309 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5310 DpmMockContext.DELEGATE_CERT_INSTALLER_UID)));
5311 });
5312 }
5313
Alex Johnston07cb9f02019-11-01 17:40:38 +00005314 public void testGetPasswordComplexity_securityExceptionNotThrownForParentInstance() {
5315 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
5316 setAsProfileOwner(admin1);
5317
5318 new DevicePolicyManagerTestable(
5319 mServiceContext,
5320 dpms,
5321 /* parentInstance= */ true)
5322 .getPasswordComplexity();
5323
5324 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
Bernard Chaue9586552018-11-29 10:59:31 +00005325 }
5326
5327 public void testGetPasswordComplexity_illegalStateExceptionIfLocked() {
5328 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5329 .thenReturn(false);
5330 assertThrows(IllegalStateException.class, () -> dpm.getPasswordComplexity());
5331 }
5332
5333 public void testGetPasswordComplexity_securityExceptionWithoutPermissions() {
5334 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5335 .thenReturn(true);
5336 assertThrows(SecurityException.class, () -> dpm.getPasswordComplexity());
5337 }
5338
5339
5340 public void testGetPasswordComplexity_currentUserNoPassword() {
5341 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5342 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005343 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005344 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5345 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
5346
5347 assertEquals(PASSWORD_COMPLEXITY_NONE, dpm.getPasswordComplexity());
5348 }
5349
5350 public void testGetPasswordComplexity_currentUserHasPassword() {
5351 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5352 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005353 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005354 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5355 .thenReturn(DpmMockContext.CALLER_USER_HANDLE);
Rubin Xu19854862019-08-15 16:37:23 +01005356 when(getServices().lockSettingsInternal
5357 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005358 .thenReturn(computeForPassword("asdf".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005359
5360 assertEquals(PASSWORD_COMPLEXITY_MEDIUM, dpm.getPasswordComplexity());
5361 }
5362
5363 public void testGetPasswordComplexity_unifiedChallengeReturnsParentUserPassword() {
5364 when(getServices().userManager.isUserUnlocked(DpmMockContext.CALLER_USER_HANDLE))
5365 .thenReturn(true);
bernardchau7ac9a712019-03-11 16:37:44 +00005366 mServiceContext.permissions.add(permission.REQUEST_PASSWORD_COMPLEXITY);
Bernard Chaue9586552018-11-29 10:59:31 +00005367
5368 UserInfo parentUser = new UserInfo();
5369 parentUser.id = DpmMockContext.CALLER_USER_HANDLE + 10;
5370 when(getServices().userManager.getCredentialOwnerProfile(DpmMockContext.CALLER_USER_HANDLE))
5371 .thenReturn(parentUser.id);
5372
Rubin Xu19854862019-08-15 16:37:23 +01005373 when(getServices().lockSettingsInternal
5374 .getUserPasswordMetrics(DpmMockContext.CALLER_USER_HANDLE))
Pavel Grafov6f334842019-08-06 14:37:06 +01005375 .thenReturn(computeForPassword("asdf".getBytes()));
Rubin Xu19854862019-08-15 16:37:23 +01005376 when(getServices().lockSettingsInternal
5377 .getUserPasswordMetrics(parentUser.id))
Pavel Grafov6f334842019-08-06 14:37:06 +01005378 .thenReturn(computeForPassword("parentUser".getBytes()));
Bernard Chaue9586552018-11-29 10:59:31 +00005379
5380 assertEquals(PASSWORD_COMPLEXITY_HIGH, dpm.getPasswordComplexity());
5381 }
5382
yuemingwd2bfbc82019-01-02 11:42:25 +00005383 public void testCrossProfileCalendarPackages_initiallyEmpty() {
5384 setAsProfileOwner(admin1);
5385 final Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5386 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5387 }
5388
5389 public void testCrossProfileCalendarPackages_reopenDpms() {
5390 setAsProfileOwner(admin1);
5391 dpm.setCrossProfileCalendarPackages(admin1, null);
5392 Set<String> packages = dpm.getCrossProfileCalendarPackages(admin1);
5393 assertTrue(packages == null);
5394 initializeDpms();
5395 packages = dpm.getCrossProfileCalendarPackages(admin1);
5396 assertTrue(packages == null);
5397
5398 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5399 packages = dpm.getCrossProfileCalendarPackages(admin1);
5400 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5401 initializeDpms();
5402 packages = dpm.getCrossProfileCalendarPackages(admin1);
5403 assertCrossProfileCalendarPackagesEqual(packages, Collections.emptySet());
5404
5405 final String dummyPackageName = "test";
5406 final Set<String> testPackages = new ArraySet<String>(Arrays.asList(dummyPackageName));
5407 dpm.setCrossProfileCalendarPackages(admin1, testPackages);
5408 packages = dpm.getCrossProfileCalendarPackages(admin1);
5409 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5410 initializeDpms();
5411 packages = dpm.getCrossProfileCalendarPackages(admin1);
5412 assertCrossProfileCalendarPackagesEqual(packages, testPackages);
5413 }
5414
5415 private void assertCrossProfileCalendarPackagesEqual(Set<String> expected, Set<String> actual) {
5416 assertTrue(expected != null);
5417 assertTrue(actual != null);
5418 assertTrue(expected.containsAll(actual));
5419 assertTrue(actual.containsAll(expected));
5420 }
5421
yuemingwdded98f2019-01-30 17:08:12 +00005422 public void testIsPackageAllowedToAccessCalendar_adminNotAllowed() {
5423 setAsProfileOwner(admin1);
5424 dpm.setCrossProfileCalendarPackages(admin1, Collections.emptySet());
5425 when(getServices().settings.settingsSecureGetIntForUser(
5426 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5427 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5428 assertFalse(dpm.isPackageAllowedToAccessCalendar("TEST_PACKAGE"));
5429 }
5430
5431 public void testIsPackageAllowedToAccessCalendar_settingOff() {
5432 final String testPackage = "TEST_PACKAGE";
5433 setAsProfileOwner(admin1);
5434 dpm.setCrossProfileCalendarPackages(admin1, Collections.singleton(testPackage));
5435 when(getServices().settings.settingsSecureGetIntForUser(
5436 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5437 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(0);
5438 assertFalse(dpm.isPackageAllowedToAccessCalendar(testPackage));
5439 }
5440
5441 public void testIsPackageAllowedToAccessCalendar_bothAllowed() {
5442 final String testPackage = "TEST_PACKAGE";
5443 setAsProfileOwner(admin1);
5444 dpm.setCrossProfileCalendarPackages(admin1, null);
5445 when(getServices().settings.settingsSecureGetIntForUser(
5446 Settings.Secure.CROSS_PROFILE_CALENDAR_ENABLED,
5447 0, DpmMockContext.CALLER_USER_HANDLE)).thenReturn(1);
5448 assertTrue(dpm.isPackageAllowedToAccessCalendar(testPackage));
5449 }
5450
Eran Messeri18d21312019-11-14 22:44:40 +00005451 private void configureProfileOwnerOfOrgOwnedDevice(ComponentName who, int userId) {
Eran Messerib8c46e02019-11-07 12:06:18 +00005452 when(getServices().userManager.getProfileParent(eq(UserHandle.of(userId))))
5453 .thenReturn(UserHandle.SYSTEM);
Eran Messeribb271892018-10-17 18:27:50 +01005454 final long ident = mServiceContext.binder.clearCallingIdentity();
5455 mServiceContext.binder.callingUid =
5456 UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, DpmMockContext.SYSTEM_UID);
Eran Messeri18d21312019-11-14 22:44:40 +00005457
5458 configureContextForAccess(mServiceContext, true);
Eran Messeribb271892018-10-17 18:27:50 +01005459 runAsCaller(mServiceContext, dpms, dpm -> {
Eran Messeri18d21312019-11-14 22:44:40 +00005460 dpm.markProfileOwnerOnOrganizationOwnedDevice(who);
Eran Messeribb271892018-10-17 18:27:50 +01005461 });
5462 mServiceContext.binder.restoreCallingIdentity(ident);
5463 }
5464
arangelov08d534b2018-01-22 15:20:53 +00005465 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5466 private void assertDeviceOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5467 writeFakeTransferMetadataFile(UserHandle.USER_SYSTEM,
5468 TransferOwnershipMetadataManager.ADMIN_TYPE_DEVICE_OWNER);
5469
5470 final long ident = mServiceContext.binder.clearCallingIdentity();
5471 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
5472 setUpPackageManagerForFakeAdmin(adminAnotherPackage,
5473 DpmMockContext.CALLER_SYSTEM_USER_UID, admin1);
5474 // To simulate a reboot, we just reinitialize dpms and call systemReady
5475 initializeDpms();
5476
5477 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
5478 assertFalse(dpm.isDeviceOwnerApp(adminAnotherPackage.getPackageName()));
5479 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5480 assertTrue(dpm.isAdminActive(admin1));
5481 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
5482 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
5483
5484 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
5485 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
5486 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
5487 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5488
5489 mServiceContext.binder.restoreCallingIdentity(ident);
5490 }
5491
5492 // admin1 is the outgoing DPC, adminAnotherPakcage is the incoming one.
5493 private void assertProfileOwnershipRevertedWithFakeTransferMetadata() throws Exception {
5494 writeFakeTransferMetadataFile(DpmMockContext.CALLER_USER_HANDLE,
5495 TransferOwnershipMetadataManager.ADMIN_TYPE_PROFILE_OWNER);
5496
5497 int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
5498 DpmMockContext.CALLER_SYSTEM_USER_UID);
5499 setUpPackageManagerForAdmin(admin1, uid);
5500 setUpPackageManagerForFakeAdmin(adminAnotherPackage, uid, admin1);
5501 // To simulate a reboot, we just reinitialize dpms and call systemReady
5502 initializeDpms();
5503
5504 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
5505 assertTrue(dpm.isAdminActive(admin1));
5506 assertFalse(dpm.isProfileOwnerApp(adminAnotherPackage.getPackageName()));
5507 assertFalse(dpm.isAdminActive(adminAnotherPackage));
5508 assertEquals(dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE), admin1);
5509 assertFalse(getMockTransferMetadataManager().metadataFileExists());
5510 }
5511
5512 private void writeFakeTransferMetadataFile(int callerUserHandle, String adminType) {
5513 TransferOwnershipMetadataManager metadataManager = getMockTransferMetadataManager();
5514 metadataManager.deleteMetadataFile();
5515
5516 final TransferOwnershipMetadataManager.Metadata metadata =
5517 new TransferOwnershipMetadataManager.Metadata(
5518 admin1.flattenToString(), adminAnotherPackage.flattenToString(),
5519 callerUserHandle,
5520 adminType);
5521 metadataManager.saveMetadataFile(metadata);
5522 }
5523
5524 private File getDeviceOwnerFile() {
5525 return dpms.mOwners.getDeviceOwnerFile();
5526 }
5527
5528 private File getProfileOwnerFile() {
5529 return dpms.mOwners.getProfileOwnerFile(DpmMockContext.CALLER_USER_HANDLE);
5530 }
5531
5532 private File getProfileOwnerPoliciesFile() {
5533 File parentDir = dpms.mMockInjector.environmentGetUserSystemDirectory(
5534 DpmMockContext.CALLER_USER_HANDLE);
5535 return getPoliciesFile(parentDir);
5536 }
5537
5538 private File getDeviceOwnerPoliciesFile() {
5539 return getPoliciesFile(getServices().systemUserDataDir);
5540 }
5541
5542 private File getPoliciesFile(File parentDir) {
5543 return new File(parentDir, "device_policies.xml");
5544 }
5545
5546 private InputStream getRawStream(@RawRes int id) {
5547 return mRealTestContext.getResources().openRawResource(id);
5548 }
5549
Victor Chang3e794af2016-03-04 13:48:17 +00005550 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005551 when(getServices().settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
Victor Chang3e794af2016-03-04 13:48:17 +00005552 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
5553 dpms.notifyChangeToContentObserver(
5554 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
5555 }
5556
5557 private void assertProvisioningAllowed(String action, boolean expected) {
5558 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
5559 dpm.isProvisioningAllowed(action));
5560 }
Tony Mak2f26b792016-11-28 17:54:51 +00005561
Nicolas Prevot45d29072017-01-18 16:11:19 +00005562 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
5563 int uid) {
Pavel Grafov75c0a892017-05-18 17:28:27 +01005564 final String previousPackageName = mContext.packageName;
5565 final int previousUid = mMockContext.binder.callingUid;
Nicolas Prevot45d29072017-01-18 16:11:19 +00005566
5567 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
5568 mContext.packageName = packageName;
5569 mMockContext.binder.callingUid = uid;
5570 assertProvisioningAllowed(action, expected);
5571
5572 // Set the previous package name / calling uid to go back to the initial state.
5573 mContext.packageName = previousPackageName;
5574 mMockContext.binder.callingUid = previousUid;
5575 }
5576
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005577 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00005578 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
5579 }
5580
5581 private void assertCheckProvisioningPreCondition(
5582 String action, String packageName, int provisioningCondition) {
5583 assertEquals("checkProvisioningPreCondition("
5584 + action + ", " + packageName + ") returning unexpected result",
5585 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00005586 }
5587
Tony Mak2f26b792016-11-28 17:54:51 +00005588 /**
5589 * Setup a managed profile with the specified admin and its uid.
5590 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
5591 * @param adminUid uid of the admin package.
5592 * @param copyFromAdmin package information for {@code admin} will be built based on this
5593 * component's information.
5594 */
5595 private void addManagedProfile(
5596 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
5597 final int userId = UserHandle.getUserId(adminUid);
Pavel Grafov75c0a892017-05-18 17:28:27 +01005598 getServices().addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
Tony Mak2f26b792016-11-28 17:54:51 +00005599 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
5600 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
5601 dpm.setActiveAdmin(admin, false, userId);
5602 assertTrue(dpm.setProfileOwner(admin, null, userId));
5603 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
5604 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00005605
5606 /**
Robin Leeabaa0692017-02-20 20:54:22 +00005607 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00005608 */
Robin Leeabaa0692017-02-20 20:54:22 +00005609 private static StringParceledListSlice asSlice(String[] s) {
5610 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00005611 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005612
5613 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00005614 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
5615 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005616
Robin Lee2c68dad2017-03-17 12:50:24 +00005617 // We can't let exceptions happen on the background thread. Throw them here if they happen
5618 // so they still cause the test to fail despite being suppressed.
Pavel Grafov75c0a892017-05-18 17:28:27 +01005619 getServices().rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01005620 }
Victor Chang3e794af2016-03-04 13:48:17 +00005621}