blob: fb74d056f9a0deaa5695656aac67d9da7509d38d [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 Grafov6a40f092016-10-25 15:46:51 +010018import static android.os.UserManagerInternal.CAMERA_DISABLED_GLOBALLY;
19import static android.os.UserManagerInternal.CAMERA_DISABLED_LOCALLY;
20import static android.os.UserManagerInternal.CAMERA_NOT_DISABLED;
21
Makoto Onukif76b06a2015-09-22 15:03:44 -070022import android.Manifest.permission;
23import android.app.Activity;
Robin Lee7f5c91c2017-02-08 21:27:02 +000024import android.app.Notification;
25import android.app.NotificationManager;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070026import android.app.admin.DeviceAdminReceiver;
27import android.app.admin.DevicePolicyManager;
28import android.app.admin.DevicePolicyManagerInternal;
Eric Sandnessfabfcb02017-05-03 18:28:56 +010029import android.app.admin.PasswordMetrics;
Makoto Onukif76b06a2015-09-22 15:03:44 -070030import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070031import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000032import android.content.Context;
33import android.content.Intent;
34import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000035import android.content.pm.ApplicationInfo;
36import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070037import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000038import android.content.pm.StringParceledListSlice;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010039import android.content.res.Resources;
40import android.graphics.Color;
41import android.net.IIpConnectivityMetrics;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +010042import android.net.Uri;
Tony Mak2f26b792016-11-28 17:54:51 +000043import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080044import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080045import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070046import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000047import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080048import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070049import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070050import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010051import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080052import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010053import android.security.IKeyChainService;
54import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000055import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080056import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000057import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010058import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070059import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070060
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010061import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000062import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000063import com.android.server.LocalServices;
64import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000065import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000066
Robin Lee7f5c91c2017-02-08 21:27:02 +000067import org.hamcrest.BaseMatcher;
68import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070069import org.mockito.invocation.InvocationOnMock;
70import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070071
Makoto Onukic8a5a552015-11-19 14:29:12 -080072import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000073import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000074import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070075import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070076import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070077import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010078import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000079import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070080
Edman Anjosf9946772016-11-28 16:35:15 +010081import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
82import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
83
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070084import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070085import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000086import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010087import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070088import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070089import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070090import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000091import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070092import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070093import static org.mockito.Mockito.doReturn;
Robin Lee7f5c91c2017-02-08 21:27:02 +000094import static org.mockito.Mockito.mock;
Robin Leed2a73ed2016-12-19 09:07:16 +000095import static org.mockito.Mockito.never;
Eric Sandnessa9b82532017-04-07 18:17:12 +010096import static org.mockito.Mockito.nullable;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080097import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000098import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070099import static org.mockito.Mockito.times;
100import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +0000101import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700102import static org.mockito.Mockito.when;
Paul Duffin192bb0b2017-03-09 18:49:41 +0000103import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700104
105/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700106 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000107 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700108 m FrameworksServicesTests &&
109 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000110 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700111 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800112 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700113
114 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000115 *
116 * , or:
117 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700118 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000119@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700120public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000121 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
122 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
123 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
124
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700125 private DpmMockContext mContext;
126 public DevicePolicyManager dpm;
127 public DevicePolicyManagerServiceTestable dpms;
128
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100129 /*
130 * The CA cert below is the content of cacert.pem as generated by:
131 *
132 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
133 */
134 private static final String TEST_CA =
135 "-----BEGIN CERTIFICATE-----\n" +
136 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
137 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
138 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
139 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
140 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
141 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
142 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
143 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
144 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
145 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
146 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
147 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
148 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
149 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
150 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
151 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
152 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
153 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
154 "wQ==\n" +
155 "-----END CERTIFICATE-----\n";
156
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700157 @Override
158 protected void setUp() throws Exception {
159 super.setUp();
160
161 mContext = getContext();
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700162 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
163 .thenReturn(true);
164
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800165 // By default, pretend all users are running and unlocked.
166 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
167
Makoto Onukia52562c2015-10-01 16:12:31 -0700168 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700169
Makoto Onukid932f762015-09-29 16:53:38 -0700170 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
171 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
172 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800173 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700174
Makoto Onukib643fb02015-09-22 15:03:44 -0700175 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700176 }
177
Robin Lee2c68dad2017-03-17 12:50:24 +0000178 @Override
179 protected void tearDown() throws Exception {
180 flushTasks();
181 super.tearDown();
182 }
183
Makoto Onukia52562c2015-10-01 16:12:31 -0700184 private void initializeDpms() {
185 // Need clearCallingIdentity() to pass permission checks.
186 final long ident = mContext.binder.clearCallingIdentity();
187 try {
188 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
189
190 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
191
192 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
193 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
194
195 dpm = new DevicePolicyManagerTestable(mContext, dpms);
196 } finally {
197 mContext.binder.restoreCallingIdentity(ident);
198 }
199 }
200
Makoto Onukib643fb02015-09-22 15:03:44 -0700201 private void setUpUserManager() {
202 // Emulate UserManager.set/getApplicationRestriction().
203 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
204
205 // UM.setApplicationRestrictions() will save to appRestrictions.
206 doAnswer(new Answer<Void>() {
207 @Override
208 public Void answer(InvocationOnMock invocation) throws Throwable {
209 String pkg = (String) invocation.getArguments()[0];
210 Bundle bundle = (Bundle) invocation.getArguments()[1];
211 UserHandle user = (UserHandle) invocation.getArguments()[2];
212
213 appRestrictions.put(Pair.create(pkg, user), bundle);
214
215 return null;
216 }
217 }).when(mContext.userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100218 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700219
220 // UM.getApplicationRestrictions() will read from appRestrictions.
221 doAnswer(new Answer<Bundle>() {
222 @Override
223 public Bundle answer(InvocationOnMock invocation) throws Throwable {
224 String pkg = (String) invocation.getArguments()[0];
225 UserHandle user = (UserHandle) invocation.getArguments()[1];
226
227 return appRestrictions.get(Pair.create(pkg, user));
228 }
229 }).when(mContext.userManager).getApplicationRestrictions(
230 anyString(), any(UserHandle.class));
231
Makoto Onukid932f762015-09-29 16:53:38 -0700232 // Add the first secondary user.
233 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700234 }
235
236 private void setAsProfileOwner(ComponentName admin) {
237 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
238 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
239
Makoto Onukia4f11972015-10-01 13:19:58 -0700240 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700241 dpm.setActiveAdmin(admin, /* replace =*/ false);
242
243 // Fire!
244 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
245
246 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700247 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700248 }
249
250 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700251 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
252 .thenReturn(false);
253
254 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
255 new DevicePolicyManagerServiceTestable(mContext, dataDir);
256
257 // If the device has no DPMS feature, it shouldn't register the local service.
258 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
259 }
260
261 /**
262 * Caller doesn't have proper permissions.
263 */
264 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700265 // 1. Failure cases.
266
267 // Caller doesn't have MANAGE_DEVICE_ADMINS.
268 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700269 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700270 fail("Didn't throw SecurityException");
271 } catch (SecurityException expected) {
272 }
273
274 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
275 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
276 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700277 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700278 fail("Didn't throw SecurityException");
279 } catch (SecurityException expected) {
280 }
281 }
282
Makoto Onukif76b06a2015-09-22 15:03:44 -0700283 /**
284 * Test for:
285 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800286 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700287 * {@link DevicePolicyManager#isAdminActive}
288 * {@link DevicePolicyManager#isAdminActiveAsUser}
289 * {@link DevicePolicyManager#getActiveAdmins}
290 * {@link DevicePolicyManager#getActiveAdminsAsUser}
291 */
292 public void testSetActiveAdmin() throws Exception {
293 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700294 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
295
Makoto Onukif76b06a2015-09-22 15:03:44 -0700296 // 2. Call the API.
297 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700298
299 // 3. Verify internal calls.
300
301 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700302 verify(mContext.spiedContext).sendBroadcastAsUser(
303 MockUtils.checkIntentAction(
304 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
305 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
306 verify(mContext.spiedContext).sendBroadcastAsUser(
307 MockUtils.checkIntentAction(
308 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700309 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
310
Makoto Onukif76b06a2015-09-22 15:03:44 -0700311 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
312 eq(admin1.getPackageName()),
313 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
314 eq(PackageManager.DONT_KILL_APP),
315 eq(DpmMockContext.CALLER_USER_HANDLE),
316 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700317
318 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700319
320 // Make sure it's active admin1.
321 assertTrue(dpm.isAdminActive(admin1));
322 assertFalse(dpm.isAdminActive(admin2));
323 assertFalse(dpm.isAdminActive(admin3));
324
325 // But not admin1 for a different user.
326
327 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
328 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
329 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
330
331 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
332 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
333
334 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
335
336 // Next, add one more admin.
337 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700338 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
339 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700340
341 dpm.setActiveAdmin(admin2, /* replace =*/ false);
342
343 // Now we have two admins.
344 assertTrue(dpm.isAdminActive(admin1));
345 assertTrue(dpm.isAdminActive(admin2));
346 assertFalse(dpm.isAdminActive(admin3));
347
348 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
349 // again. (times(1) because it was previously called for admin1)
350 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
351 eq(admin1.getPackageName()),
352 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
353 eq(PackageManager.DONT_KILL_APP),
354 eq(DpmMockContext.CALLER_USER_HANDLE),
355 anyString());
356
357 // 4. Add the same admin1 again without replace, which should throw.
358 try {
359 dpm.setActiveAdmin(admin1, /* replace =*/ false);
360 fail("Didn't throw");
361 } catch (IllegalArgumentException expected) {
362 }
363
364 // 5. Add the same admin1 again with replace, which should succeed.
365 dpm.setActiveAdmin(admin1, /* replace =*/ true);
366
367 // TODO make sure it's replaced.
368
369 // 6. Test getActiveAdmins()
370 List<ComponentName> admins = dpm.getActiveAdmins();
371 assertEquals(2, admins.size());
372 assertEquals(admin1, admins.get(0));
373 assertEquals(admin2, admins.get(1));
374
375 // Another user has no admins.
376 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
377
378 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
379 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
380
381 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
382 }
383
Makoto Onukid932f762015-09-29 16:53:38 -0700384 public void testSetActiveAdmin_multiUsers() throws Exception {
385
386 final int ANOTHER_USER_ID = 100;
387 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
388
389 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
390
391 // Set up pacakge manager for the other user.
392 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700393
394 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
395
396 dpm.setActiveAdmin(admin1, /* replace =*/ false);
397
398 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
399 dpm.setActiveAdmin(admin2, /* replace =*/ false);
400
401
402 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
403 assertTrue(dpm.isAdminActive(admin1));
404 assertFalse(dpm.isAdminActive(admin2));
405
406 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
407 assertFalse(dpm.isAdminActive(admin1));
408 assertTrue(dpm.isAdminActive(admin2));
409 }
410
Makoto Onukif76b06a2015-09-22 15:03:44 -0700411 /**
412 * Test for:
413 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800414 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700415 */
416 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
417 // 1. Make sure the caller has proper permissions.
418 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
419
420 dpm.setActiveAdmin(admin1, /* replace =*/ false);
421 assertTrue(dpm.isAdminActive(admin1));
422
423 // Add the same admin1 again without replace, which should throw.
424 try {
425 dpm.setActiveAdmin(admin1, /* replace =*/ false);
426 fail("Didn't throw");
427 } catch (IllegalArgumentException expected) {
428 }
429 }
430
431 /**
432 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800433 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
434 * BIND_DEVICE_ADMIN.
435 */
436 public void testSetActiveAdmin_permissionCheck() throws Exception {
437 // 1. Make sure the caller has proper permissions.
438 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
439
440 try {
441 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
442 fail();
443 } catch (IllegalArgumentException expected) {
444 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
445 }
446 assertFalse(dpm.isAdminActive(adminNoPerm));
447
448 // Change the target API level to MNC. Now it can be set as DA.
449 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
450 VERSION_CODES.M);
451 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
452 assertTrue(dpm.isAdminActive(adminNoPerm));
453
454 // TODO Test the "load from the file" case where DA will still be loaded even without
455 // BIND_DEVICE_ADMIN and target API is N.
456 }
457
458 /**
459 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700460 * {@link DevicePolicyManager#removeActiveAdmin}
461 */
462 public void testRemoveActiveAdmin_SecurityException() {
463 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
464
465 // Add admin.
466
467 dpm.setActiveAdmin(admin1, /* replace =*/ false);
468
469 assertTrue(dpm.isAdminActive(admin1));
470
471 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
472
473 // Directly call the DPMS method with a different userid, which should fail.
474 try {
475 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
476 fail("Didn't throw SecurityException");
477 } catch (SecurityException expected) {
478 }
479
480 // Try to remove active admin with a different caller userid should fail too, without
481 // having MANAGE_DEVICE_ADMINS.
482 mContext.callerPermissions.clear();
483
Makoto Onukid932f762015-09-29 16:53:38 -0700484 // Change the caller, and call into DPMS directly with a different user-id.
485
Makoto Onukif76b06a2015-09-22 15:03:44 -0700486 mContext.binder.callingUid = 1234567;
487 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700488 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700489 fail("Didn't throw SecurityException");
490 } catch (SecurityException expected) {
491 }
492 }
493
494 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800495 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
496 * (because we can't send the remove broadcast).
497 */
498 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
499 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
500
501 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
502
503 // Add admin.
504
505 dpm.setActiveAdmin(admin1, /* replace =*/ false);
506
507 assertTrue(dpm.isAdminActive(admin1));
508
509 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
510
511 // 1. User not unlocked.
512 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
513 .thenReturn(false);
514 try {
515 dpm.removeActiveAdmin(admin1);
516 fail("Didn't throw IllegalStateException");
517 } catch (IllegalStateException expected) {
518 MoreAsserts.assertContainsRegex(
519 "User must be running and unlocked", expected.getMessage());
520 }
521
522 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
523
524 // 2. User unlocked.
525 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
526 .thenReturn(true);
527
528 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700529 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800530 }
531
532 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700533 * Test for:
534 * {@link DevicePolicyManager#removeActiveAdmin}
535 */
Makoto Onukid932f762015-09-29 16:53:38 -0700536 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700537 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
538
539 // Add admin1.
540
541 dpm.setActiveAdmin(admin1, /* replace =*/ false);
542
543 assertTrue(dpm.isAdminActive(admin1));
544 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
545
546 // Different user, but should work, because caller has proper permissions.
547 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700548
549 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700550 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700551
552 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700553 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700554
555 // TODO DO Still can't be removed in this case.
556 }
557
558 /**
559 * Test for:
560 * {@link DevicePolicyManager#removeActiveAdmin}
561 */
562 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
563 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
564 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
565
566 // Add admin1.
567
568 dpm.setActiveAdmin(admin1, /* replace =*/ false);
569
570 assertTrue(dpm.isAdminActive(admin1));
571 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
572
573 // Broadcast from saveSettingsLocked().
574 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
575 MockUtils.checkIntentAction(
576 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
577 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
578
579 // Remove. No permissions, but same user, so it'll work.
580 mContext.callerPermissions.clear();
581 dpm.removeActiveAdmin(admin1);
582
Makoto Onukif76b06a2015-09-22 15:03:44 -0700583 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
584 MockUtils.checkIntentAction(
585 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
586 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
587 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700588 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700589 eq(dpms.mHandler),
590 eq(Activity.RESULT_OK),
591 isNull(String.class),
592 isNull(Bundle.class));
593
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700594 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700595
596 // Again broadcast from saveSettingsLocked().
597 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
598 MockUtils.checkIntentAction(
599 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
600 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
601
602 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700603 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700604
605 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000606 * Test for: @{link DevicePolicyManager#setActivePasswordState}
607 *
608 * Validates that when the password for a user changes, the notification broadcast intent
609 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
610 * addition to ones in the original user.
611 */
612 public void testSetActivePasswordState_sendToProfiles() throws Exception {
613 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
614
615 final int MANAGED_PROFILE_USER_ID = 78;
616 final int MANAGED_PROFILE_ADMIN_UID =
617 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
618
619 // Setup device owner.
620 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
621 mContext.packageName = admin1.getPackageName();
622 setupDeviceOwner();
623
624 // Add a managed profile belonging to the system user.
625 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
626
627 // Change the parent user's password.
628 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
629
630 // Both the device owner and the managed profile owner should receive this broadcast.
631 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
632 intent.setComponent(admin1);
633 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
634
635 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
636 MockUtils.checkIntent(intent),
637 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
638 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
639 MockUtils.checkIntent(intent),
640 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
641 }
642
643 /**
644 * Test for: @{link DevicePolicyManager#setActivePasswordState}
645 *
646 * Validates that when the password for a managed profile changes, the notification broadcast
647 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
648 * its parent.
649 */
650 public void testSetActivePasswordState_notSentToParent() throws Exception {
651 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
652
653 final int MANAGED_PROFILE_USER_ID = 78;
654 final int MANAGED_PROFILE_ADMIN_UID =
655 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
656
657 // Setup device owner.
658 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
659 mContext.packageName = admin1.getPackageName();
660 doReturn(true).when(mContext.lockPatternUtils)
661 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
662 setupDeviceOwner();
663
664 // Add a managed profile belonging to the system user.
665 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
666
667 // Change the profile's password.
668 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
669
670 // Both the device owner and the managed profile owner should receive this broadcast.
671 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
672 intent.setComponent(admin1);
673 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
674
675 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
676 MockUtils.checkIntent(intent),
677 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
678 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
679 MockUtils.checkIntent(intent),
680 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
681 }
682 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000683 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700684 */
685 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000686 setDeviceOwner();
687
688 // Try to set a profile owner on the same user, which should fail.
689 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
690 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
691 try {
692 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
693 fail("IllegalStateException not thrown");
694 } catch (IllegalStateException expected) {
695 assertTrue("Message was: " + expected.getMessage(),
696 expected.getMessage().contains("already has a device owner"));
697 }
698
699 // DO admin can't be deactivated.
700 dpm.removeActiveAdmin(admin1);
701 assertTrue(dpm.isAdminActive(admin1));
702
703 // TODO Test getDeviceOwnerName() too. To do so, we need to change
704 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
705 }
706
707 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700708 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800709 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700710 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
711 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
712
Makoto Onukid932f762015-09-29 16:53:38 -0700713 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700714 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
715
Makoto Onukid932f762015-09-29 16:53:38 -0700716 // Make sure admin1 is installed on system user.
717 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700718
Makoto Onukic8a5a552015-11-19 14:29:12 -0800719 // Check various get APIs.
720 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
721
Makoto Onukib643fb02015-09-22 15:03:44 -0700722 // DO needs to be an DA.
723 dpm.setActiveAdmin(admin1, /* replace =*/ false);
724
725 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700726 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700727
Makoto Onukic8a5a552015-11-19 14:29:12 -0800728 // getDeviceOwnerComponent should return the admin1 component.
729 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
730 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
731
732 // Check various get APIs.
733 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
734
735 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
736 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
737 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
738 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
739
740 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
741
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000742 // Verify internal calls.
743 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
744 eq(admin1.getPackageName()));
745
Makoto Onukib643fb02015-09-22 15:03:44 -0700746 // TODO We should check if the caller has called clearCallerIdentity().
747 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
748 eq(UserHandle.USER_SYSTEM), eq(false));
749
750 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
751 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
752 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
753
Makoto Onukic8a5a552015-11-19 14:29:12 -0800754 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700755 }
756
Makoto Onukic8a5a552015-11-19 14:29:12 -0800757 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
758 final int origCallingUser = mContext.binder.callingUid;
759 final List origPermissions = new ArrayList(mContext.callerPermissions);
760 mContext.callerPermissions.clear();
761
762 mContext.callerPermissions.add(permission.MANAGE_USERS);
763
764 mContext.binder.callingUid = Process.SYSTEM_UID;
765
766 // TODO Test getDeviceOwnerName() too. To do so, we need to change
767 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
768 if (hasDeviceOwner) {
769 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
770 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
771 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
772
773 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
774 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
775 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
776 } else {
777 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
778 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
779 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
780
781 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
782 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
783 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
784 }
785
786 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
787 if (hasDeviceOwner) {
788 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
789 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
790 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
791
792 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
793 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
794 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
795 } else {
796 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
797 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
798 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
799
800 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
801 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
802 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
803 }
804
805 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
806 // Still with MANAGE_USERS.
807 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
808 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
809 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
810
811 if (hasDeviceOwner) {
812 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
813 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
814 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
815 } else {
816 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
817 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
818 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
819 }
820
821 mContext.binder.callingUid = Process.SYSTEM_UID;
822 mContext.callerPermissions.remove(permission.MANAGE_USERS);
823 // System can still call "OnAnyUser" without MANAGE_USERS.
824 if (hasDeviceOwner) {
825 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
826 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
827 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
828
829 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
830 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
831 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
832 } else {
833 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
834 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
835 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
836
837 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
838 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
839 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
840 }
841
842 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
843 // Still no MANAGE_USERS.
844 if (hasDeviceOwner) {
845 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
846 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
847 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
848 } else {
849 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
850 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
851 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
852 }
853
854 try {
855 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
856 fail();
857 } catch (SecurityException expected) {
858 }
859 try {
860 dpm.getDeviceOwnerComponentOnAnyUser();
861 fail();
862 } catch (SecurityException expected) {
863 }
864 try {
865 dpm.getDeviceOwnerUserId();
866 fail();
867 } catch (SecurityException expected) {
868 }
869 try {
870 dpm.getDeviceOwnerNameOnAnyUser();
871 fail();
872 } catch (SecurityException expected) {
873 }
874
875 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
876 // Still no MANAGE_USERS.
877 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
878 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
879 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
880
881 try {
882 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
883 fail();
884 } catch (SecurityException expected) {
885 }
886 try {
887 dpm.getDeviceOwnerComponentOnAnyUser();
888 fail();
889 } catch (SecurityException expected) {
890 }
891 try {
892 dpm.getDeviceOwnerUserId();
893 fail();
894 } catch (SecurityException expected) {
895 }
896 try {
897 dpm.getDeviceOwnerNameOnAnyUser();
898 fail();
899 } catch (SecurityException expected) {
900 }
901
902 // Restore.
903 mContext.binder.callingUid = origCallingUser;
904 mContext.callerPermissions.addAll(origPermissions);
905 }
906
907
Makoto Onukib643fb02015-09-22 15:03:44 -0700908 /**
909 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
910 */
911 public void testSetDeviceOwner_noSuchPackage() {
912 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800913 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700914 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
915 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
916
917 // Call from a process on the system user.
918 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
919
Makoto Onukib643fb02015-09-22 15:03:44 -0700920 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700921 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700922 fail("Didn't throw IllegalArgumentException");
923 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700924 assertTrue("Message was: " + expected.getMessage(),
925 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700926 }
927 }
928
929 public void testSetDeviceOwner_failures() throws Exception {
930 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
931 }
932
Makoto Onukia52562c2015-10-01 16:12:31 -0700933 public void testClearDeviceOwner() throws Exception {
934 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800935 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700936 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
937 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
938
939 // Set admin1 as a DA to the secondary user.
940 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
941
942 dpm.setActiveAdmin(admin1, /* replace =*/ false);
943
944 // Set admin 1 as the DO to the system user.
945
946 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
947 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
948 dpm.setActiveAdmin(admin1, /* replace =*/ false);
949 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
950
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000951 // Verify internal calls.
952 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
953 eq(admin1.getPackageName()));
954
Makoto Onukic8a5a552015-11-19 14:29:12 -0800955 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700956
Makoto Onuki90b89652016-01-28 14:44:18 -0800957 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Victor Chang348f6962017-01-30 16:19:13 +0000958 when(mContext.userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
959 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800960
961 assertTrue(dpm.isAdminActive(admin1));
962 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
963
Makoto Onukia52562c2015-10-01 16:12:31 -0700964 // Set up other mocks.
965 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
966
967 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700968 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700969 eq(admin1.getPackageName()),
970 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800971
972 // But first pretend the user is locked. Then it should fail.
973 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
974 try {
975 dpm.clearDeviceOwnerApp(admin1.getPackageName());
976 fail("Didn't throw IllegalStateException");
977 } catch (IllegalStateException expected) {
978 MoreAsserts.assertContainsRegex(
979 "User must be running and unlocked", expected.getMessage());
980 }
981
982 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800983 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700984 dpm.clearDeviceOwnerApp(admin1.getPackageName());
985
986 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800987 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700988
Victor Chang348f6962017-01-30 16:19:13 +0000989 verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
990 eq(false),
991 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
992
Makoto Onuki90b89652016-01-28 14:44:18 -0800993 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
994 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100995 eq(null),
996 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800997
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700998 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100999
1000 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1001 // and once for clearing it.
1002 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1003 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1004 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001005 // TODO Check other calls.
1006 }
1007
1008 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1009 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001010 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001011 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1012 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1013
1014 // Set admin1 as a DA to the secondary user.
1015 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1016
1017 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1018
1019 // Set admin 1 as the DO to the system user.
1020
1021 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1022 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1023 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1024 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1025
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001026 // Verify internal calls.
1027 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
1028 eq(admin1.getPackageName()));
1029
Makoto Onukic8a5a552015-11-19 14:29:12 -08001030 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001031
1032 // Now call clear from the secondary user, which should throw.
1033 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1034
1035 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001036 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001037 eq(admin1.getPackageName()),
1038 anyInt());
1039 try {
1040 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1041 fail("Didn't throw");
1042 } catch (SecurityException e) {
1043 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1044 }
1045
Makoto Onukic8a5a552015-11-19 14:29:12 -08001046 // DO shouldn't be removed.
1047 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001048 }
1049
Makoto Onukib643fb02015-09-22 15:03:44 -07001050 public void testSetProfileOwner() throws Exception {
1051 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001052
Makoto Onuki90b89652016-01-28 14:44:18 -08001053 // PO admin can't be deactivated.
1054 dpm.removeActiveAdmin(admin1);
1055 assertTrue(dpm.isAdminActive(admin1));
1056
Makoto Onuki803d6752015-10-30 12:58:39 -07001057 // Try setting DO on the same user, which should fail.
1058 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1059 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1060 try {
1061 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1062 fail("IllegalStateException not thrown");
1063 } catch (IllegalStateException expected) {
1064 assertTrue("Message was: " + expected.getMessage(),
1065 expected.getMessage().contains("already has a profile owner"));
1066 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001067 }
1068
Makoto Onuki90b89652016-01-28 14:44:18 -08001069 public void testClearProfileOwner() throws Exception {
1070 setAsProfileOwner(admin1);
1071
1072 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1073
1074 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1075 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1076
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001077 // First try when the user is locked, which should fail.
1078 when(mContext.userManager.isUserUnlocked(anyInt()))
1079 .thenReturn(false);
1080 try {
1081 dpm.clearProfileOwner(admin1);
1082 fail("Didn't throw IllegalStateException");
1083 } catch (IllegalStateException expected) {
1084 MoreAsserts.assertContainsRegex(
1085 "User must be running and unlocked", expected.getMessage());
1086 }
1087 // Clear, really.
1088 when(mContext.userManager.isUserUnlocked(anyInt()))
1089 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001090 dpm.clearProfileOwner(admin1);
1091
1092 // Check
1093 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001094 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001095 }
1096
Makoto Onukib643fb02015-09-22 15:03:44 -07001097 public void testSetProfileOwner_failures() throws Exception {
1098 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1099 }
1100
Makoto Onukia52562c2015-10-01 16:12:31 -07001101 public void testGetDeviceOwnerAdminLocked() throws Exception {
1102 checkDeviceOwnerWithMultipleDeviceAdmins();
1103 }
1104
1105 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1106 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1107 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1108 // make sure it gets the right component from the right user.
1109
1110 final int ANOTHER_USER_ID = 100;
1111 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1112
1113 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1114
1115 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001116 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001117 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1118 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1119
1120 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1121
Victor Change29cd472016-03-02 20:57:42 +00001122 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1123
Makoto Onukia52562c2015-10-01 16:12:31 -07001124 // Make sure the admin packge is installed to each user.
1125 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1126 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1127
1128 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1129 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1130
1131 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1132
1133
1134 // Set active admins to the users.
1135 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1136 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1137
1138 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1139 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1140
1141 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1142
1143 // Set DO on the first non-system user.
1144 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1145 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1146
Makoto Onukic8a5a552015-11-19 14:29:12 -08001147 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001148
1149 // Then check getDeviceOwnerAdminLocked().
1150 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1151 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1152 }
1153
1154 /**
1155 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001156 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1157 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001158 *
1159 * We didn't use to persist the DO component class name, but now we do, and the above method
1160 * finds the right component from a package name upon migration.
1161 */
1162 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001163 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001164 checkDeviceOwnerWithMultipleDeviceAdmins();
1165
1166 // Overwrite the device owner setting and clears the clas name.
1167 dpms.mOwners.setDeviceOwner(
1168 new ComponentName(admin2.getPackageName(), ""),
1169 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1170 dpms.mOwners.writeDeviceOwner();
1171
1172 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001173 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001174
1175 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001176 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1177 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001178 initializeDpms();
1179
1180 // Now the DO component name is a full name.
1181 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1182 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001183 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001184 }
1185
Makoto Onukib643fb02015-09-22 15:03:44 -07001186 public void testSetGetApplicationRestriction() {
1187 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001188 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001189
1190 {
1191 Bundle rest = new Bundle();
1192 rest.putString("KEY_STRING", "Foo1");
1193 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1194 }
1195
1196 {
1197 Bundle rest = new Bundle();
1198 rest.putString("KEY_STRING", "Foo2");
1199 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1200 }
1201
1202 {
1203 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1204 assertNotNull(returned);
1205 assertEquals(returned.size(), 1);
1206 assertEquals(returned.get("KEY_STRING"), "Foo1");
1207 }
1208
1209 {
1210 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1211 assertNotNull(returned);
1212 assertEquals(returned.size(), 1);
1213 assertEquals(returned.get("KEY_STRING"), "Foo2");
1214 }
1215
1216 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1217 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1218 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001219
Edman Anjosf9946772016-11-28 16:35:15 +01001220 /**
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001221 * Setup a package in the package manager mock for {@link DpmMockContext#CALLER_USER_HANDLE}.
1222 * Useful for faking installed applications.
Edman Anjosf9946772016-11-28 16:35:15 +01001223 *
1224 * @param packageName the name of the package to be setup
1225 * @param appId the application ID to be given to the package
1226 * @return the UID of the package as known by the mock package manager
1227 */
1228 private int setupPackageInPackageManager(final String packageName, final int appId)
1229 throws Exception {
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001230 return setupPackageInPackageManager(
1231 packageName, DpmMockContext.CALLER_USER_HANDLE, appId,
1232 ApplicationInfo.FLAG_HAS_CODE);
1233 }
1234
1235 /**
1236 * Setup a package in the package manager mock. Useful for faking installed applications.
1237 *
1238 * @param packageName the name of the package to be setup
1239 * @param userId the user id where the package will be "installed"
1240 * @param appId the application ID to be given to the package
1241 * @param flags flags to set in the ApplicationInfo for this package
1242 * @return the UID of the package as known by the mock package manager
1243 */
1244 private int setupPackageInPackageManager(
1245 final String packageName, int userId, final int appId, int flags)
1246 throws Exception {
Edman Anjosf9946772016-11-28 16:35:15 +01001247 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1248 final PackageInfo pi = new PackageInfo();
1249 pi.applicationInfo = new ApplicationInfo();
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001250 pi.applicationInfo.flags = flags;
Edman Anjosf9946772016-11-28 16:35:15 +01001251 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1252 eq(packageName),
1253 anyInt(),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001254 eq(userId));
1255 doReturn(pi.applicationInfo).when(mContext.ipackageManager).getApplicationInfo(
1256 eq(packageName),
1257 anyInt(),
1258 eq(userId));
1259
Edman Anjosf9946772016-11-28 16:35:15 +01001260 // Setup application UID with the PackageManager
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001261 final int uid = UserHandle.getUid(userId, appId);
Edman Anjosf9946772016-11-28 16:35:15 +01001262 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1263 eq(packageName),
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01001264 eq(userId));
Edman Anjosf9946772016-11-28 16:35:15 +01001265 // Associate packageName to uid
1266 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1267 doReturn(new String[]{packageName})
1268 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1269 return uid;
1270 }
1271
Robin Lee7f5c91c2017-02-08 21:27:02 +00001272 public void testCertificateDisclosure() throws Exception {
1273 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1274 final UserHandle user = UserHandle.of(userId);
1275
1276 mContext.applicationInfo = new ApplicationInfo();
1277 mContext.callerPermissions.add(permission.MANAGE_USERS);
1278 mContext.packageName = "com.android.frameworks.servicestests";
Robin Lee2c68dad2017-03-17 12:50:24 +00001279 mContext.addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001280 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1281
Robin Leeabaa0692017-02-20 20:54:22 +00001282 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1283 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001284
1285 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1286 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1287
1288 // Given that we have exactly one certificate installed,
1289 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1290 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001291 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001292 // a notification should not be shown.
1293 verify(mContext.notificationManager, timeout(1000))
1294 .cancelAsUser(anyString(), anyInt(), eq(user));
1295
1296 // Given that we have four certificates installed,
1297 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1298 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001299 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1300 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001301 // a notification should be shown saying that there are two certificates left to approve.
1302 verify(mContext.notificationManager, timeout(1000))
1303 .notifyAsUser(anyString(), anyInt(), argThat(
1304 new BaseMatcher<Notification>() {
1305 @Override
1306 public boolean matches(Object item) {
1307 final Notification noti = (Notification) item;
1308 return TEST_STRING.equals(
1309 noti.extras.getString(Notification.EXTRA_TITLE));
1310 }
1311 @Override
1312 public void describeTo(Description description) {
1313 description.appendText(
1314 "Notification{title=\"" + TEST_STRING + "\"}");
1315 }
1316 }), eq(user));
1317 }
1318
Edman Anjosf9946772016-11-28 16:35:15 +01001319 /**
1320 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1321 * privileges can acually be exercised by a delegate are not covered here.
1322 */
1323 public void testDelegation() throws Exception {
1324 setAsProfileOwner(admin1);
1325
1326 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1327
1328 // Given two packages
1329 final String CERT_DELEGATE = "com.delegate.certs";
1330 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1331 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1332 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1333 20989);
1334
1335 // On delegation
1336 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1337 mContext.packageName = admin1.getPackageName();
1338 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1339 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1340
1341 // DPMS correctly stores and retrieves the delegates
1342 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1343 assertEquals(2, policy.mDelegationMap.size());
1344 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1345 DELEGATION_CERT_INSTALL);
1346 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1347 DELEGATION_CERT_INSTALL);
1348 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1349 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1350 DELEGATION_APP_RESTRICTIONS);
1351 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1352 DELEGATION_APP_RESTRICTIONS);
1353 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1354
1355 // On calling install certificate APIs from an unauthorized process
1356 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1357 mContext.packageName = RESTRICTIONS_DELEGATE;
1358
1359 // DPMS throws a SecurityException
1360 try {
1361 dpm.installCaCert(null, null);
1362 fail("Didn't throw SecurityException on unauthorized access");
1363 } catch (SecurityException expected) {
1364 }
1365
1366 // On calling install certificate APIs from an authorized process
1367 mContext.binder.callingUid = CERT_DELEGATE_UID;
1368 mContext.packageName = CERT_DELEGATE;
1369
1370 // DPMS executes without a SecurityException
1371 try {
1372 dpm.installCaCert(null, null);
1373 } catch (SecurityException unexpected) {
1374 fail("Threw SecurityException on authorized access");
1375 } catch (NullPointerException expected) {
1376 }
1377
1378 // On removing a delegate
1379 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1380 mContext.packageName = admin1.getPackageName();
1381 dpm.setCertInstallerPackage(admin1, null);
1382
1383 // DPMS does not allow access to ex-delegate
1384 mContext.binder.callingUid = CERT_DELEGATE_UID;
1385 mContext.packageName = CERT_DELEGATE;
1386 try {
1387 dpm.installCaCert(null, null);
1388 fail("Didn't throw SecurityException on unauthorized access");
1389 } catch (SecurityException expected) {
1390 }
1391
1392 // But still allows access to other existing delegates
1393 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1394 mContext.packageName = RESTRICTIONS_DELEGATE;
1395 try {
1396 dpm.getApplicationRestrictions(null, "pkg");
1397 } catch (SecurityException expected) {
1398 fail("Threw SecurityException on authorized access");
1399 }
1400 }
1401
Esteban Talaverabf60f722015-12-10 16:26:44 +00001402 public void testApplicationRestrictionsManagingApp() throws Exception {
1403 setAsProfileOwner(admin1);
1404
Rubin Xued1928a2016-02-11 17:23:06 +00001405 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001406 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1407 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001408 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1409 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001410
Esteban Talaverabf60f722015-12-10 16:26:44 +00001411 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1412 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001413 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1414 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001415 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1416 Bundle rest = new Bundle();
1417 rest.putString("KEY_STRING", "Foo1");
1418 try {
1419 dpm.setApplicationRestrictions(null, "pkg1", rest);
1420 fail("Didn't throw expected SecurityException");
1421 } catch (SecurityException expected) {
1422 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001423 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1424 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001425 }
1426 try {
1427 dpm.getApplicationRestrictions(null, "pkg1");
1428 fail("Didn't throw expected SecurityException");
1429 } catch (SecurityException expected) {
1430 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001431 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1432 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001433 }
1434
1435 // Check via the profile owner that no restrictions were set.
1436 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001437 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001438 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1439
Rubin Xued1928a2016-02-11 17:23:06 +00001440 // Check the API does not allow setting a non-existent package
1441 try {
1442 dpm.setApplicationRestrictionsManagingPackage(admin1,
1443 nonExistAppRestrictionsManagerPackage);
1444 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001445 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001446 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001447 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001448 }
1449
Esteban Talaverabf60f722015-12-10 16:26:44 +00001450 // Let appRestrictionsManagerPackage manage app restrictions
1451 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1452 assertEquals(appRestrictionsManagerPackage,
1453 dpm.getApplicationRestrictionsManagingPackage(admin1));
1454
1455 // Now that package should be able to set and retrieve app restrictions.
1456 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001457 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001458 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1459 dpm.setApplicationRestrictions(null, "pkg1", rest);
1460 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1461 assertEquals(1, returned.size(), 1);
1462 assertEquals("Foo1", returned.get("KEY_STRING"));
1463
1464 // The same app running on a separate user shouldn't be able to manage app restrictions.
1465 mContext.binder.callingUid = UserHandle.getUid(
1466 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1467 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1468 try {
1469 dpm.setApplicationRestrictions(null, "pkg1", rest);
1470 fail("Didn't throw expected SecurityException");
1471 } catch (SecurityException expected) {
1472 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001473 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1474 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001475 }
1476
1477 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1478 // too.
1479 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001480 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001481 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1482 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1483 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1484
1485 // Removing the ability for the package to manage app restrictions.
1486 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1487 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1488 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001489 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001490 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1491 try {
1492 dpm.setApplicationRestrictions(null, "pkg1", null);
1493 fail("Didn't throw expected SecurityException");
1494 } catch (SecurityException expected) {
1495 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001496 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1497 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001498 }
1499 }
1500
Makoto Onukia4f11972015-10-01 13:19:58 -07001501 public void testSetUserRestriction_asDo() throws Exception {
1502 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001503 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001504 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1505 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1506
1507 // First, set DO.
1508
1509 // Call from a process on the system user.
1510 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1511
1512 // Make sure admin1 is installed on system user.
1513 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001514
1515 // Call.
1516 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001517 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001518 UserHandle.USER_SYSTEM));
1519
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001520 // Check that the user restrictions that are enabled by default are set. Then unset them.
1521 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001522 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001523 DpmTestUtils.assertRestrictions(
1524 DpmTestUtils.newRestrictions(defaultRestrictions),
1525 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1526 );
1527 DpmTestUtils.assertRestrictions(
1528 DpmTestUtils.newRestrictions(defaultRestrictions),
1529 dpm.getUserRestrictions(admin1)
1530 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001531 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1532 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001533 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001534 eq(true) /* isDeviceOwner */,
1535 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001536 );
1537 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001538
1539 for (String restriction : defaultRestrictions) {
1540 dpm.clearUserRestriction(admin1, restriction);
1541 }
1542
Esteban Talavera548a04b2016-12-20 15:22:30 +00001543 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001544 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001545
1546 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1547 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1548 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001549 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1550 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001551 reset(mContext.userManagerInternal);
1552
Makoto Onukia4f11972015-10-01 13:19:58 -07001553 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001554 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1555 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001556 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1557 UserManager.DISALLOW_ADD_USER),
1558 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001559 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001560
Makoto Onuki068c54a2015-10-13 14:34:03 -07001561 DpmTestUtils.assertRestrictions(
1562 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001563 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001564 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1565 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001566 DpmTestUtils.assertRestrictions(
1567 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001568 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001569 dpm.getUserRestrictions(admin1)
1570 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001571
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001572 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1573 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1574 eq(UserHandle.USER_SYSTEM),
1575 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001576 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001577 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001578
Makoto Onuki068c54a2015-10-13 14:34:03 -07001579 DpmTestUtils.assertRestrictions(
1580 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1581 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1582 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001583 DpmTestUtils.assertRestrictions(
1584 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1585 dpm.getUserRestrictions(admin1)
1586 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001587
1588 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001589 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1590 eq(UserHandle.USER_SYSTEM),
1591 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001592 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001593 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001594
Esteban Talavera548a04b2016-12-20 15:22:30 +00001595 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001596
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001597 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1598 // DO sets them, the scope is global.
1599 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1600 reset(mContext.userManagerInternal);
1601 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1602 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1603 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001604 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001605 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1606 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001607 reset(mContext.userManagerInternal);
1608
1609 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1610 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001611 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612
1613 // More tests.
1614 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1615 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1616 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001617 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1618 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001619 reset(mContext.userManagerInternal);
1620
1621 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1622 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1623 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001624 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 UserManager.DISALLOW_ADD_USER),
1626 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001627 reset(mContext.userManagerInternal);
1628
1629 dpm.setCameraDisabled(admin1, true);
1630 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1631 eq(UserHandle.USER_SYSTEM),
1632 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001633 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001634 UserManager.DISALLOW_ADD_USER),
1635 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001636 reset(mContext.userManagerInternal);
1637
1638 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1639 // locally.
1640 dpm.setCameraDisabled(admin1, false);
1641 reset(mContext.userManagerInternal);
1642
1643 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1644 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1645 dpm.setCameraDisabled(admin2, true);
1646
1647 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1648 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001649 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001651 UserManager.DISALLOW_ADD_USER),
1652 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001653 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001654 // TODO Make sure restrictions are written to the file.
1655 }
1656
1657 public void testSetUserRestriction_asPo() {
1658 setAsProfileOwner(admin1);
1659
Makoto Onuki068c54a2015-10-13 14:34:03 -07001660 DpmTestUtils.assertRestrictions(
1661 DpmTestUtils.newRestrictions(),
1662 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1663 .ensureUserRestrictions()
1664 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001665
1666 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001667 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1668 eq(DpmMockContext.CALLER_USER_HANDLE),
1669 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001670 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001671 reset(mContext.userManagerInternal);
1672
Makoto Onukia4f11972015-10-01 13:19:58 -07001673 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1675 eq(DpmMockContext.CALLER_USER_HANDLE),
1676 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1677 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001678 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001679 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001680
Makoto Onuki068c54a2015-10-13 14:34:03 -07001681 DpmTestUtils.assertRestrictions(
1682 DpmTestUtils.newRestrictions(
1683 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1684 UserManager.DISALLOW_OUTGOING_CALLS
1685 ),
1686 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1687 .ensureUserRestrictions()
1688 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001689 DpmTestUtils.assertRestrictions(
1690 DpmTestUtils.newRestrictions(
1691 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1692 UserManager.DISALLOW_OUTGOING_CALLS
1693 ),
1694 dpm.getUserRestrictions(admin1)
1695 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001696
1697 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001698 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1699 eq(DpmMockContext.CALLER_USER_HANDLE),
1700 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001701 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001702 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001703
1704 DpmTestUtils.assertRestrictions(
1705 DpmTestUtils.newRestrictions(
1706 UserManager.DISALLOW_OUTGOING_CALLS
1707 ),
1708 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1709 .ensureUserRestrictions()
1710 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001711 DpmTestUtils.assertRestrictions(
1712 DpmTestUtils.newRestrictions(
1713 UserManager.DISALLOW_OUTGOING_CALLS
1714 ),
1715 dpm.getUserRestrictions(admin1)
1716 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001717
1718 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001719 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1720 eq(DpmMockContext.CALLER_USER_HANDLE),
1721 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001722 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001723 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001724
Makoto Onuki068c54a2015-10-13 14:34:03 -07001725 DpmTestUtils.assertRestrictions(
1726 DpmTestUtils.newRestrictions(),
1727 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1728 .ensureUserRestrictions()
1729 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001730 DpmTestUtils.assertRestrictions(
1731 DpmTestUtils.newRestrictions(),
1732 dpm.getUserRestrictions(admin1)
1733 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001734
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001735 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1736 // though when DO sets them they'll be applied globally.
1737 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1738 reset(mContext.userManagerInternal);
1739 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1740 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1741 eq(DpmMockContext.CALLER_USER_HANDLE),
1742 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1743 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001744 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001745 reset(mContext.userManagerInternal);
1746
1747 dpm.setCameraDisabled(admin1, true);
1748 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1749 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001750 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001751 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001752 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001753 reset(mContext.userManagerInternal);
1754
Makoto Onukia4f11972015-10-01 13:19:58 -07001755 // TODO Make sure restrictions are written to the file.
1756 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001757
Esteban Talavera548a04b2016-12-20 15:22:30 +00001758
1759 public void testDefaultEnabledUserRestrictions() throws Exception {
1760 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1761 mContext.callerPermissions.add(permission.MANAGE_USERS);
1762 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1763 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1764
1765 // First, set DO.
1766
1767 // Call from a process on the system user.
1768 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1769
1770 // Make sure admin1 is installed on system user.
1771 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1772
1773 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1774 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1775 UserHandle.USER_SYSTEM));
1776
1777 // Check that the user restrictions that are enabled by default are set. Then unset them.
1778 String[] defaultRestrictions = UserRestrictionsUtils
1779 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1780 assertTrue(defaultRestrictions.length > 0);
1781 DpmTestUtils.assertRestrictions(
1782 DpmTestUtils.newRestrictions(defaultRestrictions),
1783 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1784 );
1785 DpmTestUtils.assertRestrictions(
1786 DpmTestUtils.newRestrictions(defaultRestrictions),
1787 dpm.getUserRestrictions(admin1)
1788 );
1789 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1790 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001791 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001792 eq(true) /* isDeviceOwner */,
1793 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001794 );
1795 reset(mContext.userManagerInternal);
1796
1797 for (String restriction : defaultRestrictions) {
1798 dpm.clearUserRestriction(admin1, restriction);
1799 }
1800
1801 assertNoDeviceOwnerRestrictions();
1802
1803 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1804 reset(mContext.userManagerInternal);
1805 initializeDpms();
1806 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1807 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1808
1809 assertNoDeviceOwnerRestrictions();
1810
1811 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1812 // is set as it wasn't enabled during setDeviceOwner.
1813 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1814 assertFalse(UserRestrictionsUtils
1815 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1816 UserRestrictionsUtils
1817 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1818 try {
1819 reset(mContext.userManagerInternal);
1820 initializeDpms();
1821 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1822 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1823
1824 DpmTestUtils.assertRestrictions(
1825 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1826 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1827 );
1828 DpmTestUtils.assertRestrictions(
1829 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1830 dpm.getUserRestrictions(admin1)
1831 );
1832 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1833 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001834 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001835 eq(true) /* isDeviceOwner */,
1836 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001837 );
1838 reset(mContext.userManagerInternal);
1839
1840 // Remove the restriction.
1841 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1842
1843 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1844 initializeDpms();
1845 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1846 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1847 assertNoDeviceOwnerRestrictions();
1848 } finally {
1849 UserRestrictionsUtils
1850 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1851 }
1852 }
1853
1854 private void assertNoDeviceOwnerRestrictions() {
1855 DpmTestUtils.assertRestrictions(
1856 DpmTestUtils.newRestrictions(),
1857 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1858 );
1859 DpmTestUtils.assertRestrictions(
1860 DpmTestUtils.newRestrictions(),
1861 dpm.getUserRestrictions(admin1)
1862 );
1863 }
1864
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001865 public void testGetMacAddress() throws Exception {
1866 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1867 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1868 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1869
1870 // In this test, change the caller user to "system".
1871 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1872
1873 // Make sure admin1 is installed on system user.
1874 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1875
1876 // Test 1. Caller doesn't have DO or DA.
1877 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001878 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001879 fail();
1880 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001881 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001882 }
1883
1884 // DO needs to be an DA.
1885 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1886 assertTrue(dpm.isAdminActive(admin1));
1887
1888 // Test 2. Caller has DA, but not DO.
1889 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001890 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001891 fail();
1892 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001893 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001894 }
1895
1896 // Test 3. Caller has PO, but not DO.
1897 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1898 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001899 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001900 fail();
1901 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001902 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001903 }
1904
1905 // Remove PO.
1906 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001907 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001908 // Test 4, Caller is DO now.
1909 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1910
1911 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001912 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001913
1914 // 4-2. Returns WifiInfo, but with the default MAC.
1915 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001916 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001917
1918 // 4-3. With a real MAC address.
1919 final WifiInfo wi = new WifiInfo();
1920 wi.setMacAddress("11:22:33:44:55:66");
1921 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001922 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001923 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001924
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001925 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001926 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1927 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1928
1929 // In this test, change the caller user to "system".
1930 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1931
1932 // Make sure admin1 is installed on system user.
1933 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1934
1935 // Set admin1 as DA.
1936 dpm.setActiveAdmin(admin1, false);
1937 assertTrue(dpm.isAdminActive(admin1));
1938 try {
1939 dpm.reboot(admin1);
1940 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1941 } catch (SecurityException expected) {
1942 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1943 }
1944
1945 // Set admin1 as PO.
1946 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1947 try {
1948 dpm.reboot(admin1);
1949 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1950 } catch (SecurityException expected) {
1951 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1952 }
1953
1954 // Remove PO and add DO.
1955 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001956 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001957 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1958
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001959 // admin1 is DO.
1960 // Set current call state of device to ringing.
1961 when(mContext.telephonyManager.getCallState())
1962 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1963 try {
1964 dpm.reboot(admin1);
1965 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1966 } catch (IllegalStateException expected) {
1967 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1968 }
1969
1970 // Set current call state of device to dialing/active.
1971 when(mContext.telephonyManager.getCallState())
1972 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1973 try {
1974 dpm.reboot(admin1);
1975 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1976 } catch (IllegalStateException expected) {
1977 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1978 }
1979
1980 // Set current call state of device to idle.
1981 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001982 dpm.reboot(admin1);
1983 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001984
1985 public void testSetGetSupportText() {
1986 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1987 dpm.setActiveAdmin(admin1, true);
1988 dpm.setActiveAdmin(admin2, true);
1989 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1990
1991 // Null default support messages.
1992 {
1993 assertNull(dpm.getLongSupportMessage(admin1));
1994 assertNull(dpm.getShortSupportMessage(admin1));
1995 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1996 assertNull(dpm.getShortSupportMessageForUser(admin1,
1997 DpmMockContext.CALLER_USER_HANDLE));
1998 assertNull(dpm.getLongSupportMessageForUser(admin1,
1999 DpmMockContext.CALLER_USER_HANDLE));
2000 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2001 }
2002
2003 // Only system can call the per user versions.
2004 {
2005 try {
2006 dpm.getShortSupportMessageForUser(admin1,
2007 DpmMockContext.CALLER_USER_HANDLE);
2008 fail("Only system should be able to call getXXXForUser versions");
2009 } catch (SecurityException expected) {
2010 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
2011 }
2012 try {
2013 dpm.getLongSupportMessageForUser(admin1,
2014 DpmMockContext.CALLER_USER_HANDLE);
2015 fail("Only system should be able to call getXXXForUser versions");
2016 } catch (SecurityException expected) {
2017 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
2018 }
2019 }
2020
2021 // Can't set message for admin in another uid.
2022 {
2023 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
2024 try {
2025 dpm.setShortSupportMessage(admin1, "Some text");
2026 fail("Admins should only be able to change their own support text.");
2027 } catch (SecurityException expected) {
2028 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
2029 }
2030 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2031 }
2032
2033 // Set/Get short returns what it sets and other admins text isn't changed.
2034 {
2035 final String supportText = "Some text to test with.";
2036 dpm.setShortSupportMessage(admin1, supportText);
2037 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2038 assertNull(dpm.getLongSupportMessage(admin1));
2039 assertNull(dpm.getShortSupportMessage(admin2));
2040
2041 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2042 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2043 DpmMockContext.CALLER_USER_HANDLE));
2044 assertNull(dpm.getShortSupportMessageForUser(admin2,
2045 DpmMockContext.CALLER_USER_HANDLE));
2046 assertNull(dpm.getLongSupportMessageForUser(admin1,
2047 DpmMockContext.CALLER_USER_HANDLE));
2048 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2049
2050 dpm.setShortSupportMessage(admin1, null);
2051 assertNull(dpm.getShortSupportMessage(admin1));
2052 }
2053
2054 // Set/Get long returns what it sets and other admins text isn't changed.
2055 {
2056 final String supportText = "Some text to test with.\nWith more text.";
2057 dpm.setLongSupportMessage(admin1, supportText);
2058 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2059 assertNull(dpm.getShortSupportMessage(admin1));
2060 assertNull(dpm.getLongSupportMessage(admin2));
2061
2062 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2063 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2064 DpmMockContext.CALLER_USER_HANDLE));
2065 assertNull(dpm.getLongSupportMessageForUser(admin2,
2066 DpmMockContext.CALLER_USER_HANDLE));
2067 assertNull(dpm.getShortSupportMessageForUser(admin1,
2068 DpmMockContext.CALLER_USER_HANDLE));
2069 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2070
2071 dpm.setLongSupportMessage(admin1, null);
2072 assertNull(dpm.getLongSupportMessage(admin1));
2073 }
2074 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002075
phweiss73145f42017-01-17 19:06:38 +01002076 public void testCreateAdminSupportIntent() throws Exception {
2077 // Setup device owner.
2078 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2079 setupDeviceOwner();
2080
2081 // Nonexisting permission returns null
2082 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2083 assertNull(intent);
2084
2085 // Existing permission that is not set returns null
2086 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2087 assertNull(intent);
2088
2089 // Existing permission that is not set by device/profile owner returns null
2090 when(mContext.userManager.hasUserRestriction(
2091 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2092 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2093 .thenReturn(true);
2094 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2095 assertNull(intent);
2096
2097 // Permission that is set by device owner returns correct intent
2098 when(mContext.userManager.getUserRestrictionSource(
2099 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2100 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2101 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2102 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2103 assertNotNull(intent);
2104 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2105 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2106 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2107 assertEquals(admin1,
2108 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2109 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2110 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2111
2112 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2113 // user restrictions
2114
2115 // Camera is not disabled
2116 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2117 assertNull(intent);
2118
2119 // Camera is disabled
2120 dpm.setCameraDisabled(admin1, true);
2121 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2122 assertNotNull(intent);
2123 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2124 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2125
2126 // Screen capture is not disabled
2127 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2128 assertNull(intent);
2129
2130 // Screen capture is disabled
2131 dpm.setScreenCaptureDisabled(admin1, true);
2132 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2133 assertNotNull(intent);
2134 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2135 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2136
2137 // Same checks for different user
2138 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2139 // Camera should be disabled by device owner
2140 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2141 assertNotNull(intent);
2142 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2143 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2144 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2145 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2146 // ScreenCapture should not be disabled by device owner
2147 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2148 assertNull(intent);
2149 }
2150
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002151 /**
2152 * Test for:
2153 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002154 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002155 * {@link DevicePolicyManager#isAffiliatedUser}
2156 */
2157 public void testUserAffiliation() throws Exception {
2158 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2159 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2160 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2161
2162 // Check that the system user is unaffiliated.
2163 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2164 assertFalse(dpm.isAffiliatedUser());
2165
2166 // Set a device owner on the system user. Check that the system user becomes affiliated.
2167 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2168 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2169 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2170 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002171 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002172
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002173 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002174 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2175 setAsProfileOwner(admin2);
2176 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002177 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002178
2179 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2180 // unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002181 final Set<String> userAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002182 userAffiliationIds.add("red");
2183 userAffiliationIds.add("green");
2184 userAffiliationIds.add("blue");
2185 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002186 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002187 assertFalse(dpm.isAffiliatedUser());
2188
2189 // Have the device owner specify a set of affiliation ids that do not intersect with those
2190 // specified by the profile owner. Check that the test user remains unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002191 final Set<String> deviceAffiliationIds = new ArraySet<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002192 deviceAffiliationIds.add("cyan");
2193 deviceAffiliationIds.add("yellow");
2194 deviceAffiliationIds.add("magenta");
2195 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2196 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002197 MoreAsserts.assertContentsInAnyOrder(
2198 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002199 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2200 assertFalse(dpm.isAffiliatedUser());
2201
2202 // Have the profile owner specify a set of affiliation ids that intersect with those
2203 // specified by the device owner. Check that the test user becomes affiliated.
2204 userAffiliationIds.add("yellow");
2205 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002206 MoreAsserts.assertContentsInAnyOrder(
2207 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002208 assertTrue(dpm.isAffiliatedUser());
2209
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002210 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
Tony Mak31657432017-04-25 09:29:55 +01002211 dpm.setAffiliationIds(admin2, Collections.emptySet());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002212 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002213 assertFalse(dpm.isAffiliatedUser());
2214
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002215 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2216 dpm.setAffiliationIds(admin2, userAffiliationIds);
2217 assertTrue(dpm.isAffiliatedUser());
2218 dpm.clearProfileOwner(admin2);
2219 assertFalse(dpm.isAffiliatedUser());
2220
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002221 // Check that the system user remains affiliated.
2222 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2223 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002224
2225 // Clear the device owner - the user becomes unaffiliated.
2226 clearDeviceOwner();
2227 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002228 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002229
2230 public void testGetUserProvisioningState_defaultResult() {
2231 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2232 }
2233
2234 public void testSetUserProvisioningState_permission() throws Exception {
2235 setupProfileOwner();
2236 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2237
2238 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2239 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2240 }
2241
2242 public void testSetUserProvisioningState_unprivileged() throws Exception {
2243 setupProfileOwner();
2244 try {
2245 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2246 DpmMockContext.CALLER_USER_HANDLE);
2247 fail("Expected SecurityException");
2248 } catch (SecurityException expected) {
2249 }
2250 }
2251
2252 public void testSetUserProvisioningState_noManagement() {
2253 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2254 try {
2255 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2256 DpmMockContext.CALLER_USER_HANDLE);
2257 fail("IllegalStateException expected");
2258 } catch (IllegalStateException e) {
2259 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2260 e.getMessage());
2261 }
2262 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2263 }
2264
2265 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2266 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2267 setupDeviceOwner();
2268 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2269
2270 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2271 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2272 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2273 }
2274
2275 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2276 throws Exception {
2277 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2278 setupDeviceOwner();
2279 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2280
2281 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2282 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2283 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2284 }
2285
2286 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2287 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2288 setupDeviceOwner();
2289 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2290
2291 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2292 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2293 }
2294
2295 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2296 throws Exception {
2297 setupProfileOwner();
2298 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2299
2300 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2301 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2302 DevicePolicyManager.STATE_USER_UNMANAGED);
2303 }
2304
2305 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2306 throws Exception {
2307 setupProfileOwner();
2308 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2309
2310 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2311 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2312 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2313 }
2314
2315 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2316 setupProfileOwner();
2317 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2318
2319 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2320 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2321 }
2322
2323 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2324 setupProfileOwner();
2325 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2326
2327 try {
2328 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2329 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2330 DevicePolicyManager.STATE_USER_UNMANAGED);
2331 fail("Expected IllegalStateException");
2332 } catch (IllegalStateException e) {
2333 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2334 e.getMessage());
2335 }
2336 }
2337
2338 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2339 throws Exception {
2340 setupProfileOwner();
2341 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2342
2343 try {
2344 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2345 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2346 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2347 fail("Expected IllegalStateException");
2348 } catch (IllegalStateException e) {
2349 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2350 e.getMessage());
2351 }
2352 }
2353
2354 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2355 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2356 for (int state : states) {
2357 dpm.setUserProvisioningState(state, userId);
2358 assertEquals(state, dpm.getUserProvisioningState());
2359 }
2360 }
2361
2362 private void setupProfileOwner() throws Exception {
2363 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2364
2365 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2366 dpm.setActiveAdmin(admin1, false);
2367 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2368
2369 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2370 }
2371
2372 private void setupDeviceOwner() throws Exception {
2373 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2374
2375 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2376 dpm.setActiveAdmin(admin1, false);
2377 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2378
2379 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2380 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002381
2382 public void testSetMaximumTimeToLock() {
2383 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2384
2385 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2386 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2387
2388 reset(mMockContext.powerManagerInternal);
2389 reset(mMockContext.settings);
2390
2391 dpm.setMaximumTimeToLock(admin1, 0);
2392 verifyScreenTimeoutCall(null, false);
2393 reset(mMockContext.powerManagerInternal);
2394 reset(mMockContext.settings);
2395
2396 dpm.setMaximumTimeToLock(admin1, 1);
2397 verifyScreenTimeoutCall(1, true);
2398 reset(mMockContext.powerManagerInternal);
2399 reset(mMockContext.settings);
2400
2401 dpm.setMaximumTimeToLock(admin2, 10);
2402 verifyScreenTimeoutCall(null, false);
2403 reset(mMockContext.powerManagerInternal);
2404 reset(mMockContext.settings);
2405
2406 dpm.setMaximumTimeToLock(admin1, 5);
2407 verifyScreenTimeoutCall(5, true);
2408 reset(mMockContext.powerManagerInternal);
2409 reset(mMockContext.settings);
2410
2411 dpm.setMaximumTimeToLock(admin2, 4);
2412 verifyScreenTimeoutCall(4, true);
2413 reset(mMockContext.powerManagerInternal);
2414 reset(mMockContext.settings);
2415
2416 dpm.setMaximumTimeToLock(admin1, 0);
2417 reset(mMockContext.powerManagerInternal);
2418 reset(mMockContext.settings);
2419
2420 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2421 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2422 reset(mMockContext.powerManagerInternal);
2423 reset(mMockContext.settings);
2424
2425 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2426 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2427 reset(mMockContext.powerManagerInternal);
2428 reset(mMockContext.settings);
2429
2430 dpm.setMaximumTimeToLock(admin2, 10);
2431 verifyScreenTimeoutCall(10, true);
2432 reset(mMockContext.powerManagerInternal);
2433 reset(mMockContext.settings);
2434
2435 // There's no restriction; shold be set to MAX.
2436 dpm.setMaximumTimeToLock(admin2, 0);
2437 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2438 }
2439
Michal Karpinski943aabd2016-10-06 11:09:25 +01002440 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2441 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2442 setupDeviceOwner();
2443 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2444
Michal Karpinskid084ca52017-01-18 15:54:18 +00002445 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2446 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2447 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2448 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2449 - ONE_MINUTE;
2450
2451 // verify that the minimum timeout cannot be modified on user builds (system property is
2452 // not being read)
2453 mContext.buildMock.isDebuggable = false;
2454
2455 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2456 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2457 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2458
2459 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2460
2461 // restore to the debuggable build state
2462 mContext.buildMock.isDebuggable = true;
2463
2464 // Always return the default (second arg) when getting system property for long type
2465 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2466 new Answer<Long>() {
2467 @Override
2468 public Long answer(InvocationOnMock invocation) throws Throwable {
2469 return (Long) invocation.getArguments()[1];
2470 }
2471 }
2472 );
2473
2474 // reset to default (0 means the admin is not participating, so default should be returned)
2475 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002476
2477 // aggregation should be the default if unset by any admin
2478 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2479 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2480
2481 // admin not participating by default
2482 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2483
2484 //clamping from the top
2485 dpm.setRequiredStrongAuthTimeout(admin1,
2486 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2487 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2488 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2489 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2490 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2491
Michal Karpinskid084ca52017-01-18 15:54:18 +00002492 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002493 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2494 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2495 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2496 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2497
2498 // clamping from the bottom
2499 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2500 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2501 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2502
Michal Karpinskid084ca52017-01-18 15:54:18 +00002503 // values within range
2504 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2505 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2506 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2507
2508 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2509 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2510 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002511
2512 // reset to default
2513 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2514 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2515 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2516 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2517
2518 // negative value
2519 try {
2520 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2521 fail("Didn't throw IllegalArgumentException");
2522 } catch (IllegalArgumentException iae) {
2523 }
2524 }
2525
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002526 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2527 boolean shouldStayOnWhilePluggedInBeCleared) {
2528 if (expectedTimeout == null) {
2529 verify(mMockContext.powerManagerInternal, times(0))
2530 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2531 } else {
2532 verify(mMockContext.powerManagerInternal, times(1))
2533 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2534 }
2535 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2536 // UnfinishedVerificationException.
2537 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002538
Esteban Talavera01576862016-12-15 11:16:44 +00002539 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002540 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2541 .thenReturn(false);
2542 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2543 .thenReturn(false);
2544 initializeDpms();
2545 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2546 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2547 .thenReturn(true);
2548 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2549
2550 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002551 }
Victor Chang3e794af2016-03-04 13:48:17 +00002552
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002553 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2554 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002555 mContext.packageName = admin1.getPackageName();
2556 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002557 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2558 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2559 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2560 false);
2561 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2562 }
2563
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002564 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2565 setup_DeviceAdminFeatureOff();
2566 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2567 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2568 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2569 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2570 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2571 assertCheckProvisioningPreCondition(
2572 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2573 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2574 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2575 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2576 }
2577
Esteban Talavera01576862016-12-15 11:16:44 +00002578 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002579 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2580 .thenReturn(false);
2581 initializeDpms();
2582 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2583 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2584 .thenReturn(true);
2585 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2586
2587 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002588 }
Victor Chang3e794af2016-03-04 13:48:17 +00002589
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002590 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2591 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002592 mContext.packageName = admin1.getPackageName();
2593 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002594 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2595 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2596 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2597 false);
2598 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2599
2600 // Test again when split user is on
2601 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2602 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2603 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2604 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2605 true);
2606 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2607 }
2608
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002609 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2610 setup_ManagedProfileFeatureOff();
2611 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2612 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2613 DevicePolicyManager.CODE_OK);
2614 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2615 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2616 assertCheckProvisioningPreCondition(
2617 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2618 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2619 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2620 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2621
2622 // Test again when split user is on
2623 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2624 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2625 DevicePolicyManager.CODE_OK);
2626 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2627 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2628 assertCheckProvisioningPreCondition(
2629 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2630 DevicePolicyManager.CODE_OK);
2631 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2632 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2633 }
2634
Esteban Talavera01576862016-12-15 11:16:44 +00002635 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002636 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2637 .thenReturn(true);
2638 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2639 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2640 .thenReturn(true);
2641 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2642
2643 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002644 }
Victor Chang3e794af2016-03-04 13:48:17 +00002645
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002646 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2647 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002648 mContext.packageName = admin1.getPackageName();
2649 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002650 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2651 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2652 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2653 false /* because of non-split user */);
2654 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2655 false /* because of non-split user */);
2656 }
2657
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002658 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002659 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002660 setup_nonSplitUser_firstBoot_primaryUser();
2661 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2662 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2663 DevicePolicyManager.CODE_OK);
2664 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2665 DevicePolicyManager.CODE_OK);
2666 assertCheckProvisioningPreCondition(
2667 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2668 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2669 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2670 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2671 }
2672
Esteban Talavera01576862016-12-15 11:16:44 +00002673 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002674 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2675 .thenReturn(true);
2676 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2677 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2678 .thenReturn(true);
2679 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2680
2681 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002682 }
Victor Chang3e794af2016-03-04 13:48:17 +00002683
Nicolas Prevot45d29072017-01-18 16:11:19 +00002684 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2685 setDeviceOwner();
2686 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2687 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2688 }
2689
2690 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2691 setup_nonSplitUser_withDo_primaryUser();
2692 final int MANAGED_PROFILE_USER_ID = 18;
2693 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2694 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2695 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2696 false /* we can't remove a managed profile */)).thenReturn(false);
2697 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2698 true)).thenReturn(true);
2699 }
2700
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002701 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2702 throws Exception {
2703 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002704 mContext.packageName = admin1.getPackageName();
2705 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002706 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2707 false/* because of completed device setup */);
2708 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2709 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2710 false/* because of non-split user */);
2711 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2712 false/* because of non-split user */);
2713 }
2714
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002715 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2716 throws Exception {
2717 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2718 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2719 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2720 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2721 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2722 DevicePolicyManager.CODE_OK);
2723 assertCheckProvisioningPreCondition(
2724 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2725 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2726 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2727 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2728 }
2729
Nicolas Prevot45d29072017-01-18 16:11:19 +00002730 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2731 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002732 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002733 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2734
2735 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2736 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002737 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002738
2739 // COMP mode is allowed.
2740 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2741 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002742 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002743
Nicolas Prevot45d29072017-01-18 16:11:19 +00002744 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002745 assertCheckProvisioningPreCondition(
2746 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002747 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002748 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002749 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2750 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2751 }
Esteban Talavera01576862016-12-15 11:16:44 +00002752
Nicolas Prevot45d29072017-01-18 16:11:19 +00002753 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2754 setup_nonSplitUser_withDo_primaryUser();
2755 mContext.packageName = admin1.getPackageName();
2756 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2757 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2758 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002759 when(mContext.userManager.hasUserRestriction(
2760 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2761 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2762 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002763 when(mContext.userManager.getUserRestrictionSource(
2764 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2765 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2766 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2767 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2768 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002769 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002770 assertCheckProvisioningPreCondition(
2771 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002772 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002773 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002774 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2775 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2776 }
Esteban Talavera01576862016-12-15 11:16:44 +00002777
Nicolas Prevot45d29072017-01-18 16:11:19 +00002778 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2779 throws Exception {
2780 setup_nonSplitUser_withDo_primaryUser();
2781 mContext.packageName = admin1.getPackageName();
2782 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002783 // The DO should not be allowed to initiate provisioning if the restriction is set by
2784 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002785 when(mContext.userManager.hasUserRestriction(
2786 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2787 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2788 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002789 when(mContext.userManager.getUserRestrictionSource(
2790 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2791 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2792 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2793 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2794 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002795 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2796
2797 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002798 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002799 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002800 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002801 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2802 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2803 }
2804
2805 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2806 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2807 mContext.packageName = admin1.getPackageName();
2808 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2809
2810 // We can delete the managed profile to create a new one, so provisioning is allowed.
2811 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2812 DevicePolicyManager.CODE_OK);
2813 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2814 assertCheckProvisioningPreCondition(
2815 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2816 DpmMockContext.ANOTHER_PACKAGE_NAME,
2817 DevicePolicyManager.CODE_OK);
2818 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2819 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2820 }
2821
2822 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2823 throws Exception {
2824 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2825 mContext.packageName = admin1.getPackageName();
2826 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2827 when(mContext.userManager.hasUserRestriction(
2828 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2829 eq(UserHandle.SYSTEM)))
2830 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002831 when(mContext.userManager.getUserRestrictionSource(
2832 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2833 eq(UserHandle.SYSTEM)))
2834 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002835
2836 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002837 assertCheckProvisioningPreCondition(
2838 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2839 DpmMockContext.ANOTHER_PACKAGE_NAME,
2840 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2842 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002843
2844 // But the device owner can still do it because it has set the restriction itself.
2845 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2846 DevicePolicyManager.CODE_OK);
2847 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002848 }
2849
2850 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002851 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2852 .thenReturn(true);
2853 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2854 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2855 .thenReturn(false);
2856 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2857
2858 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002859 }
Victor Chang3e794af2016-03-04 13:48:17 +00002860
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002861 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2862 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002863 mContext.packageName = admin1.getPackageName();
2864 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002865 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2866 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2867 false /* because canAddMoreManagedProfiles returns false */);
2868 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2869 true);
2870 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2871 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002872 }
2873
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002874 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2875 throws Exception {
2876 setup_splitUser_firstBoot_systemUser();
2877 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2878 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2879 DevicePolicyManager.CODE_OK);
2880 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002881 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002882 assertCheckProvisioningPreCondition(
2883 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2884 DevicePolicyManager.CODE_OK);
2885 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2886 DevicePolicyManager.CODE_SYSTEM_USER);
2887 }
2888
Esteban Talavera01576862016-12-15 11:16:44 +00002889 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002890 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2891 .thenReturn(true);
2892 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2893 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2894 .thenReturn(false);
2895 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2896
2897 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002898 }
Victor Chang3e794af2016-03-04 13:48:17 +00002899
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002900 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2901 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002902 mContext.packageName = admin1.getPackageName();
2903 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002904 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2905 true/* it's undefined behavior. Can be changed into false in the future */);
2906 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2907 false /* because canAddMoreManagedProfiles returns false */);
2908 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2909 true/* it's undefined behavior. Can be changed into false in the future */);
2910 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2911 false/* because calling uid is system user */);
2912 }
2913
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2915 throws Exception {
2916 setup_splitUser_afterDeviceSetup_systemUser();
2917 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2918 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2919 DevicePolicyManager.CODE_OK);
2920 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002921 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002922 assertCheckProvisioningPreCondition(
2923 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2924 DevicePolicyManager.CODE_OK);
2925 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2926 DevicePolicyManager.CODE_SYSTEM_USER);
2927 }
2928
Esteban Talavera01576862016-12-15 11:16:44 +00002929 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002930 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2931 .thenReturn(true);
2932 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2933 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2934 true)).thenReturn(true);
2935 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2936
2937 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002938 }
Victor Chang3e794af2016-03-04 13:48:17 +00002939
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002940 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2941 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002942 mContext.packageName = admin1.getPackageName();
2943 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002944 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2945 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2946 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2947 true);
2948 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002949 }
2950
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002951 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002952 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002953 setup_splitUser_firstBoot_primaryUser();
2954 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2955 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2956 DevicePolicyManager.CODE_OK);
2957 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2958 DevicePolicyManager.CODE_OK);
2959 assertCheckProvisioningPreCondition(
2960 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2961 DevicePolicyManager.CODE_OK);
2962 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2963 DevicePolicyManager.CODE_OK);
2964 }
2965
Esteban Talavera01576862016-12-15 11:16:44 +00002966 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002967 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2968 .thenReturn(true);
2969 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2970 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2971 true)).thenReturn(true);
2972 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2973
2974 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002975 }
Victor Chang3e794af2016-03-04 13:48:17 +00002976
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002977 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2978 throws Exception {
2979 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002980 mContext.packageName = admin1.getPackageName();
2981 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002982 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2983 true/* it's undefined behavior. Can be changed into false in the future */);
2984 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2985 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2986 true/* it's undefined behavior. Can be changed into false in the future */);
2987 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2988 false/* because user setup completed */);
2989 }
2990
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002991 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002992 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 setup_splitUser_afterDeviceSetup_primaryUser();
2994 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2995 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2996 DevicePolicyManager.CODE_OK);
2997 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2998 DevicePolicyManager.CODE_OK);
2999 assertCheckProvisioningPreCondition(
3000 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
3001 DevicePolicyManager.CODE_OK);
3002 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
3003 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
3004 }
3005
Esteban Talavera01576862016-12-15 11:16:44 +00003006 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003007 setDeviceOwner();
3008
3009 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3010 .thenReturn(true);
3011 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3012 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
3013 .thenReturn(false);
3014 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
3015
3016 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003017 }
Victor Chang3e794af2016-03-04 13:48:17 +00003018
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003019 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
3020 throws Exception {
3021 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003022 mContext.packageName = admin1.getPackageName();
3023 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003024 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3025 false /* can't provision managed profile on system user */);
3026 }
3027
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003028 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003029 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003030 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3031 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3032 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3033 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3034 }
3035
3036 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003037 setDeviceOwner();
3038
3039 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3040 .thenReturn(true);
3041 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3042 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3043 true)).thenReturn(true);
3044 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3045
3046 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003047 }
Victor Chang3e794af2016-03-04 13:48:17 +00003048
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003049 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3050 throws Exception {
3051 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003052 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3053 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003054 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3055 }
3056
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003057 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003058 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003059 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3060 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003061
3062 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003063 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3064 DevicePolicyManager.CODE_OK);
3065 }
3066
3067 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003068 setDeviceOwner();
3069
3070 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3071 .thenReturn(true);
3072 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003073 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003074 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3075 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003076 .thenReturn(true);
3077 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003078 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003079 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3080 true)).thenReturn(true);
3081 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3082
3083 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003084 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003085
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003086 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3087 throws Exception {
3088 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003089 mContext.packageName = admin1.getPackageName();
3090 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003091 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3092 }
3093
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003094 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3095 throws Exception {
3096 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3097 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3098 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3099 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3100 }
3101
3102 public void testCheckProvisioningPreCondition_permission() {
3103 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3104 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003105 dpm.checkProvisioningPreCondition(
3106 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003107 fail("Didn't throw SecurityException");
3108 } catch (SecurityException expected) {
3109 }
3110 }
3111
Victor Chang3577ed22016-08-25 18:49:26 +01003112 public void testForceUpdateUserSetupComplete_permission() {
3113 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3114 try {
3115 dpm.forceUpdateUserSetupComplete();
3116 fail("Didn't throw SecurityException");
3117 } catch (SecurityException expected) {
3118 }
3119 }
3120
3121 public void testForceUpdateUserSetupComplete_systemUser() {
3122 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3123 // GIVEN calling from user 20
3124 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3125 try {
3126 dpm.forceUpdateUserSetupComplete();
3127 fail("Didn't throw SecurityException");
3128 } catch (SecurityException expected) {
3129 }
3130 }
3131
3132 public void testForceUpdateUserSetupComplete_userbuild() {
3133 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3134 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3135
3136 final int userId = UserHandle.USER_SYSTEM;
3137 // GIVEN userComplete is false in SettingsProvider
3138 setUserSetupCompleteForUser(false, userId);
3139
3140 // GIVEN userComplete is true in DPM
3141 DevicePolicyManagerService.DevicePolicyData userData =
3142 new DevicePolicyManagerService.DevicePolicyData(userId);
3143 userData.mUserSetupComplete = true;
3144 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3145
3146 // GIVEN it's user build
3147 mContext.buildMock.isDebuggable = false;
3148
3149 assertTrue(dpms.hasUserSetupCompleted());
3150
3151 dpm.forceUpdateUserSetupComplete();
3152
3153 // THEN the state in dpms is not changed
3154 assertTrue(dpms.hasUserSetupCompleted());
3155 }
3156
3157 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3158 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3159 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3160
3161 final int userId = UserHandle.USER_SYSTEM;
3162 // GIVEN userComplete is false in SettingsProvider
3163 setUserSetupCompleteForUser(false, userId);
3164
3165 // GIVEN userComplete is true in DPM
3166 DevicePolicyManagerService.DevicePolicyData userData =
3167 new DevicePolicyManagerService.DevicePolicyData(userId);
3168 userData.mUserSetupComplete = true;
3169 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3170
3171 // GIVEN it's userdebug build
3172 mContext.buildMock.isDebuggable = true;
3173
3174 assertTrue(dpms.hasUserSetupCompleted());
3175
3176 dpm.forceUpdateUserSetupComplete();
3177
3178 // THEN the state in dpms is not changed
3179 assertFalse(dpms.hasUserSetupCompleted());
3180 }
3181
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003182 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003183 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003184 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3185 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3186 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3187 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003188 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003189 }
3190
3191 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3192 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3193 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003194
3195 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3196 // feature is disabled because there are non-affiliated secondary users.
3197 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003198 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3199 .thenReturn(true);
3200
3201 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003202 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003203
3204 // Enabling logging should not change the timestamp.
3205 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003206 verify(mContext.settings)
3207 .securityLogSetLoggingEnabledProperty(true);
3208 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3209 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003210 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003211
3212 // Retrieving the logs should update the timestamp.
3213 final long beforeRetrieval = System.currentTimeMillis();
3214 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003215 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003216 final long afterRetrieval = System.currentTimeMillis();
3217 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3218 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3219
3220 // Retrieving the pre-boot logs should update the timestamp.
3221 Thread.sleep(2);
3222 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003223 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003224 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3225
3226 // Checking the timestamp again should not change it.
3227 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003228 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003229
3230 // Retrieving the logs again should update the timestamp.
3231 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003232 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003233 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3234
3235 // Disabling logging should not change the timestamp.
3236 Thread.sleep(2);
3237 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003238 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003239
3240 // Restarting the DPMS should not lose the timestamp.
3241 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003242 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003243
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003244 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3245 mContext.binder.callingUid = 1234567;
3246 mContext.callerPermissions.add(permission.MANAGE_USERS);
3247 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3248 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3249
3250 // System can retrieve the timestamp.
3251 mContext.binder.clearCallingIdentity();
3252 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3253
3254 // Removing the device owner should clear the timestamp.
3255 clearDeviceOwner();
3256 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003257 }
3258
3259 public void testGetLastBugReportRequestTime() throws Exception {
3260 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3261 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003262
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003263 mContext.packageName = admin1.getPackageName();
3264 mContext.applicationInfo = new ApplicationInfo();
3265 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3266 .thenReturn(Color.WHITE);
3267 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3268 anyObject())).thenReturn(Color.WHITE);
3269
Esteban Talaverad36dd152016-12-15 08:51:45 +00003270 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3271 // feature is disabled because there are non-affiliated secondary users.
3272 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3273
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003274 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003275 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003276
3277 // Requesting a bug report should update the timestamp.
3278 final long beforeRequest = System.currentTimeMillis();
3279 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003280 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003281 final long afterRequest = System.currentTimeMillis();
3282 assertTrue(bugReportRequestTime >= beforeRequest);
3283 assertTrue(bugReportRequestTime <= afterRequest);
3284
3285 // Checking the timestamp again should not change it.
3286 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003287 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003288
3289 // Restarting the DPMS should not lose the timestamp.
3290 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003291 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003292
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003293 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3294 mContext.binder.callingUid = 1234567;
3295 mContext.callerPermissions.add(permission.MANAGE_USERS);
3296 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3297 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3298
3299 // System can retrieve the timestamp.
3300 mContext.binder.clearCallingIdentity();
3301 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3302
3303 // Removing the device owner should clear the timestamp.
3304 clearDeviceOwner();
3305 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003306 }
3307
3308 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3309 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3310 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003311 mContext.packageName = admin1.getPackageName();
3312 mContext.applicationInfo = new ApplicationInfo();
3313 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3314 .thenReturn(Color.WHITE);
3315 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3316 anyObject())).thenReturn(Color.WHITE);
3317
3318 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3319 // feature is disabled because there are non-affiliated secondary users.
3320 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003321 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3322 .thenReturn(true);
3323
3324 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003325 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003326
3327 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3328 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003329 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003330
3331 // Enabling logging should not change the timestamp.
3332 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003333 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003334
3335 // Retrieving the logs should update the timestamp.
3336 final long beforeRetrieval = System.currentTimeMillis();
3337 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003338 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003339 final long afterRetrieval = System.currentTimeMillis();
3340 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3341 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3342
3343 // Checking the timestamp again should not change it.
3344 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003345 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003346
3347 // Retrieving the logs again should update the timestamp.
3348 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003349 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003350 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3351
3352 // Disabling logging should not change the timestamp.
3353 Thread.sleep(2);
3354 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003355 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003356
3357 // Restarting the DPMS should not lose the timestamp.
3358 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003359 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3360
3361 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3362 mContext.binder.callingUid = 1234567;
3363 mContext.callerPermissions.add(permission.MANAGE_USERS);
3364 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3365 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3366
3367 // System can retrieve the timestamp.
3368 mContext.binder.clearCallingIdentity();
3369 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3370
3371 // Removing the device owner should clear the timestamp.
3372 clearDeviceOwner();
3373 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003374 }
3375
Tony Mak2f26b792016-11-28 17:54:51 +00003376 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3377 // Setup device owner.
3378 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3379 setupDeviceOwner();
3380
3381 // Only device owner is setup, the result list should be empty.
3382 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3383 MoreAsserts.assertEmpty(targetUsers);
3384
3385 // Setup a managed profile managed by the same admin.
3386 final int MANAGED_PROFILE_USER_ID = 15;
3387 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3388 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3389
3390 // Add a secondary user, it should never talk with.
3391 final int ANOTHER_USER_ID = 36;
3392 mContext.addUser(ANOTHER_USER_ID, 0);
3393
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003394 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3395 // other.
3396 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3397 MoreAsserts.assertEmpty(targetUsers);
3398
3399 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3400 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3401 MoreAsserts.assertEmpty(targetUsers);
3402
3403 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003404 final Set<String> userAffiliationIds = Collections.singleton("some.affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003405 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3406 dpm.setAffiliationIds(admin1, userAffiliationIds);
3407
3408 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3409 dpm.setAffiliationIds(admin1, userAffiliationIds);
3410
Tony Mak2f26b792016-11-28 17:54:51 +00003411 // Calling from device owner admin, the result list should just contain the managed
3412 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003413 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003414 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3415 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3416
3417 // Calling from managed profile admin, the result list should just contain the system
3418 // user id.
3419 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3420 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3421 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003422
3423 // Changing affiliation ids in one
Tony Mak31657432017-04-25 09:29:55 +01003424 dpm.setAffiliationIds(admin1, Collections.singleton("some-different-affiliation-id"));
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003425
3426 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3427 // to each other.
3428 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3429 MoreAsserts.assertEmpty(targetUsers);
3430
3431 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3432 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3433 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003434 }
3435
3436 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3437 // Setup a device owner.
3438 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3439 setupDeviceOwner();
3440
3441 // Set up a managed profile managed by different package.
3442 final int MANAGED_PROFILE_USER_ID = 15;
3443 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3444 final ComponentName adminDifferentPackage =
3445 new ComponentName("another.package", "whatever.class");
3446 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3447
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003448 // Setting affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003449 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003450 dpm.setAffiliationIds(admin1, userAffiliationIds);
3451
3452 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3453 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3454
Tony Mak2f26b792016-11-28 17:54:51 +00003455 // Calling from device owner admin, we should get zero bind device admin target users as
3456 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003457 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003458 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3459 MoreAsserts.assertEmpty(targetUsers);
3460
3461 // Calling from managed profile admin, we should still get zero target users for the same
3462 // reason.
3463 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3464 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3465 MoreAsserts.assertEmpty(targetUsers);
3466 }
3467
Esteban Talaverabdcada92017-02-01 14:20:06 +00003468 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3469 // Setup a device owner.
3470 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3471 setupDeviceOwner();
3472 // Lock task packages are updated when loading user data.
3473 verify(mContext.iactivityManager)
3474 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3475
3476 // Set up a managed profile managed by different package (package name shouldn't matter)
3477 final int MANAGED_PROFILE_USER_ID = 15;
3478 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3479 final ComponentName adminDifferentPackage =
3480 new ComponentName("another.package", "whatever.class");
3481 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3482 verify(mContext.iactivityManager)
3483 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3484
3485 // The DO can still set lock task packages
3486 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3487 final String[] doPackages = {"doPackage1", "doPackage2"};
3488 dpm.setLockTaskPackages(admin1, doPackages);
3489 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3490 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3491 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3492 verify(mContext.iactivityManager)
3493 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3494
3495 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3496 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3497 final String[] poPackages = {"poPackage1", "poPackage2"};
3498 try {
3499 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3500 fail("Didn't throw expected security exception.");
3501 } catch (SecurityException expected) {
3502 }
3503 try {
3504 dpm.getLockTaskPackages(adminDifferentPackage);
3505 fail("Didn't throw expected security exception.");
3506 } catch (SecurityException expected) {
3507 }
3508 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3509
3510 // Setting same affiliation ids
Tony Mak31657432017-04-25 09:29:55 +01003511 final Set<String> userAffiliationIds = Collections.singleton("some-affiliation-id");
Esteban Talaverabdcada92017-02-01 14:20:06 +00003512 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3513 dpm.setAffiliationIds(admin1, userAffiliationIds);
3514
3515 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3516 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3517
3518 // Now the managed profile can set lock task packages.
3519 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3520 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3521 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3522 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3523 verify(mContext.iactivityManager)
3524 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3525
3526 // Unaffiliate the profile, lock task mode no longer available on the profile.
Tony Mak31657432017-04-25 09:29:55 +01003527 dpm.setAffiliationIds(adminDifferentPackage, Collections.emptySet());
Esteban Talaverabdcada92017-02-01 14:20:06 +00003528 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3529 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3530 verify(mContext.iactivityManager, times(2))
3531 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3532
3533 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3534 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3535 }
3536
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003537 public void testIsDeviceManaged() throws Exception {
3538 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3539 setupDeviceOwner();
3540
3541 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3542 // find out that the device has a device owner.
3543 assertTrue(dpm.isDeviceManaged());
3544 mContext.binder.callingUid = 1234567;
3545 mContext.callerPermissions.add(permission.MANAGE_USERS);
3546 assertTrue(dpm.isDeviceManaged());
3547 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3548 mContext.binder.clearCallingIdentity();
3549 assertTrue(dpm.isDeviceManaged());
3550
3551 clearDeviceOwner();
3552
3553 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3554 // not have a device owner.
3555 mContext.binder.callingUid = 1234567;
3556 mContext.callerPermissions.add(permission.MANAGE_USERS);
3557 assertFalse(dpm.isDeviceManaged());
3558 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3559 mContext.binder.clearCallingIdentity();
3560 assertFalse(dpm.isDeviceManaged());
3561 }
3562
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003563 public void testDeviceOwnerOrganizationName() throws Exception {
3564 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3565 setupDeviceOwner();
3566
3567 dpm.setOrganizationName(admin1, "organization");
3568
3569 // Device owner can retrieve organization managing the device.
3570 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3571
3572 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3573 mContext.binder.callingUid = 1234567;
3574 mContext.callerPermissions.add(permission.MANAGE_USERS);
3575 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3576 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3577
3578 // System can retrieve organization managing the device.
3579 mContext.binder.clearCallingIdentity();
3580 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3581
3582 // Removing the device owner clears the organization managing the device.
3583 clearDeviceOwner();
3584 assertNull(dpm.getDeviceOwnerOrganizationName());
3585 }
3586
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003587 public void testWipeDataManagedProfile() throws Exception {
3588 final int MANAGED_PROFILE_USER_ID = 15;
3589 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3590 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3591 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3592
3593 // Even if the caller is the managed profile, the current user is the user 0
3594 when(mContext.iactivityManager.getCurrentUser())
3595 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3596
3597 dpm.wipeData(0);
3598 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3599 MANAGED_PROFILE_USER_ID);
3600 }
3601
3602 public void testWipeDataManagedProfileDisallowed() throws Exception {
3603 final int MANAGED_PROFILE_USER_ID = 15;
3604 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3605 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3606
3607 // Even if the caller is the managed profile, the current user is the user 0
3608 when(mContext.iactivityManager.getCurrentUser())
3609 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3610
3611 when(mContext.userManager.getUserRestrictionSource(
3612 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3613 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3614 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3615 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3616 try {
3617 // The PO is not allowed to remove the profile if the user restriction was set on the
3618 // profile by the system
3619 dpm.wipeData(0);
3620 fail("SecurityException not thrown");
3621 } catch (SecurityException expected) {
3622 }
3623 }
3624
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003625 public void testWipeDataDeviceOwner() throws Exception {
3626 setDeviceOwner();
3627 when(mContext.userManager.getUserRestrictionSource(
3628 UserManager.DISALLOW_FACTORY_RESET,
3629 UserHandle.SYSTEM))
3630 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3631
3632 dpm.wipeData(0);
3633 verify(mContext.recoverySystem).rebootWipeUserData(
3634 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3635 }
3636
3637 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3638 setDeviceOwner();
3639 when(mContext.userManager.getUserRestrictionSource(
3640 UserManager.DISALLOW_FACTORY_RESET,
3641 UserHandle.SYSTEM))
3642 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3643 try {
3644 // The DO is not allowed to wipe the device if the user restriction was set
3645 // by the system
3646 dpm.wipeData(0);
3647 fail("SecurityException not thrown");
3648 } catch (SecurityException expected) {
3649 }
3650 }
3651
3652 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3653 final int MANAGED_PROFILE_USER_ID = 15;
3654 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3655 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3656
3657 // Even if the caller is the managed profile, the current user is the user 0
3658 when(mContext.iactivityManager.getCurrentUser())
3659 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3660
3661 when(mContext.userManager.getUserRestrictionSource(
3662 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3663 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3664 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3665
3666 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3667 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3668
3669 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3670 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3671 // Failed password attempts on the parent user are taken into account, as there isn't a
3672 // separate work challenge.
3673 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3674 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3675 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3676
3677 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3678 // both the user restriction and the policy were set by the PO.
3679 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3680 MANAGED_PROFILE_USER_ID);
3681 verifyZeroInteractions(mContext.recoverySystem);
3682 }
3683
3684 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3685 throws Exception {
3686 final int MANAGED_PROFILE_USER_ID = 15;
3687 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3688 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3689
3690 // Even if the caller is the managed profile, the current user is the user 0
3691 when(mContext.iactivityManager.getCurrentUser())
3692 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3693
3694 when(mContext.userManager.getUserRestrictionSource(
3695 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3696 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3697 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3698
3699 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3700 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3701
3702 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3703 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3704 // Failed password attempts on the parent user are taken into account, as there isn't a
3705 // separate work challenge.
3706 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3707 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3708 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3709
3710 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3711 // not wiped.
3712 verify(mContext.userManagerInternal, never())
3713 .removeUserEvenWhenDisallowed(anyInt());
3714 verifyZeroInteractions(mContext.recoverySystem);
3715 }
3716
3717 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3718 setDeviceOwner();
3719 when(mContext.userManager.getUserRestrictionSource(
3720 UserManager.DISALLOW_FACTORY_RESET,
3721 UserHandle.SYSTEM))
3722 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3723
3724 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3725
3726 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3727 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3728 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3729 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3730 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3731
3732 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3733 // user restriction and the policy were set by the DO.
3734 verify(mContext.recoverySystem).rebootWipeUserData(
3735 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3736 }
3737
3738 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3739 setDeviceOwner();
3740 when(mContext.userManager.getUserRestrictionSource(
3741 UserManager.DISALLOW_FACTORY_RESET,
3742 UserHandle.SYSTEM))
3743 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3744
3745 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3746
3747 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3748 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3749 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3750 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3751 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3752
3753 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3754 verifyZeroInteractions(mContext.recoverySystem);
3755 verify(mContext.userManagerInternal, never())
3756 .removeUserEvenWhenDisallowed(anyInt());
3757 }
3758
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003759 public void testGetPermissionGrantState() throws Exception {
3760 final String permission = "some.permission";
3761 final String app1 = "com.example.app1";
3762 final String app2 = "com.example.app2";
3763
3764 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3765 .thenReturn(PackageManager.PERMISSION_GRANTED);
3766 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3767 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3768 when(mContext.packageManager.getPermissionFlags(permission, app1,
3769 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3770 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3771 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3772 .thenReturn(PackageManager.PERMISSION_DENIED);
3773 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3774 UserHandle.SYSTEM);
3775 when(mContext.packageManager.getPermissionFlags(permission, app2,
3776 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3777
3778 // System can retrieve permission grant state.
3779 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003780 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003781 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3782 dpm.getPermissionGrantState(null, app1, permission));
3783 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3784 dpm.getPermissionGrantState(null, app2, permission));
3785
3786 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003787 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3788 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003789 try {
3790 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003791 fail("Didn't throw SecurityException");
3792 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003793 }
3794
3795 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003796 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3797 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003798 setAsProfileOwner(admin1);
3799 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3800 dpm.getPermissionGrantState(admin1, app1, permission));
3801 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3802 dpm.getPermissionGrantState(admin1, app2, permission));
3803 }
3804
Rubin Xuaab7a412016-12-30 21:13:29 +00003805 public void testResetPasswordWithToken() throws Exception {
3806 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3807 setupDeviceOwner();
3808 // test token validation
3809 try {
3810 dpm.setResetPasswordToken(admin1, new byte[31]);
3811 fail("should not have accepted tokens too short");
3812 } catch (IllegalArgumentException expected) {
3813 }
3814 // test adding a token
3815 final byte[] token = new byte[32];
3816 final long handle = 123456;
3817 final String password = "password";
3818 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3819 .thenReturn(handle);
3820 assertTrue(dpm.setResetPasswordToken(admin1, token));
3821
3822 // test password activation
3823 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3824 .thenReturn(true);
3825 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3826
3827 // test reset password with token
3828 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3829 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3830 eq(UserHandle.USER_SYSTEM)))
3831 .thenReturn(true);
3832 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3833
3834 // test removing a token
3835 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3836 .thenReturn(true);
3837 assertTrue(dpm.clearResetPasswordToken(admin1));
3838 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003839
Eric Sandnessfabfcb02017-05-03 18:28:56 +01003840 public void testIsActivePasswordSufficient() throws Exception {
3841 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3842 mContext.packageName = admin1.getPackageName();
3843 setupDeviceOwner();
3844
3845 dpm.setPasswordQuality(admin1, DevicePolicyManager.PASSWORD_QUALITY_COMPLEX);
3846 dpm.setPasswordMinimumLength(admin1, 8);
3847 dpm.setPasswordMinimumLetters(admin1, 6);
3848 dpm.setPasswordMinimumLowerCase(admin1, 3);
3849 dpm.setPasswordMinimumUpperCase(admin1, 1);
3850 dpm.setPasswordMinimumNonLetter(admin1, 1);
3851 dpm.setPasswordMinimumNumeric(admin1, 1);
3852 dpm.setPasswordMinimumSymbols(admin1, 0);
3853
3854 PasswordMetrics passwordMetricsNoSymbols = new PasswordMetrics(
3855 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3856 8, 2,
3857 6, 1,
3858 0, 1);
3859
3860 setActivePasswordState(passwordMetricsNoSymbols);
3861 assertTrue(dpm.isActivePasswordSufficient());
3862
3863 initializeDpms();
3864 reset(mContext.spiedContext);
3865 assertTrue(dpm.isActivePasswordSufficient());
3866
3867 // This call simulates the user entering the password for the first time after a reboot.
3868 // This causes password metrics to be reloaded into memory. Until this happens,
3869 // dpm.isActivePasswordSufficient() will continue to return its last checkpointed value,
3870 // even if the DPC changes password requirements so that the password no longer meets the
3871 // requirements. This is a known limitation of the current implementation of
3872 // isActivePasswordSufficient() - see b/34218769.
3873 setActivePasswordState(passwordMetricsNoSymbols);
3874 assertTrue(dpm.isActivePasswordSufficient());
3875
3876 dpm.setPasswordMinimumSymbols(admin1, 1);
3877 // This assertion would fail if we had not called setActivePasswordState() again after
3878 // initializeDpms() - see previous comment.
3879 assertFalse(dpm.isActivePasswordSufficient());
3880
3881 initializeDpms();
3882 reset(mContext.spiedContext);
3883 assertFalse(dpm.isActivePasswordSufficient());
3884
3885 PasswordMetrics passwordMetricsWithSymbols = new PasswordMetrics(
3886 DevicePolicyManager.PASSWORD_QUALITY_COMPLEX, 9,
3887 7, 2,
3888 5, 1,
3889 1, 2);
3890
3891 setActivePasswordState(passwordMetricsWithSymbols);
3892 assertTrue(dpm.isActivePasswordSufficient());
3893 }
3894
3895 private void setActivePasswordState(PasswordMetrics passwordMetrics) {
3896 int userHandle = UserHandle.getUserId(mContext.binder.callingUid);
3897 final long ident = mContext.binder.clearCallingIdentity();
3898 try {
3899 dpm.setActivePasswordState(passwordMetrics, userHandle);
3900 dpm.reportPasswordChanged(userHandle);
3901
3902 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
3903 intent.setComponent(admin1);
3904 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(mContext.binder.callingUid));
3905
3906 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
3907 MockUtils.checkIntent(intent),
3908 MockUtils.checkUserHandle(userHandle));
3909 } finally {
3910 mContext.binder.restoreCallingIdentity(ident);
3911 }
3912 }
3913
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003914 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3915 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3916 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3917 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3918 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3919 DpmMockContext.SYSTEM_UID);
3920 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3921 DpmMockContext.SYSTEM_UID);
3922
3923 // Set up a device owner.
3924 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003925 setupDeviceOwner();
3926
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003927 // First and second user set IMEs manually.
3928 mContext.binder.callingUid = firstUserSystemUid;
3929 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3930 mContext.binder.callingUid = secondUserSystemUid;
3931 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003932
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003933 // Device owner changes IME for first user.
3934 mContext.binder.callingUid = deviceOwnerUid;
3935 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003936 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003937 dpm.setSecureSetting(admin1, currentIme, "ime2");
3938 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003939 UserHandle.USER_SYSTEM);
3940 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003941 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3942 mContext.binder.callingUid = firstUserSystemUid;
3943 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3944 mContext.binder.callingUid = secondUserSystemUid;
3945 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003946
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003947 // Second user changes IME manually.
3948 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3949 mContext.binder.callingUid = firstUserSystemUid;
3950 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3951 mContext.binder.callingUid = secondUserSystemUid;
3952 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003953
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003954 // First user changes IME manually.
3955 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3956 mContext.binder.callingUid = firstUserSystemUid;
3957 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3958 mContext.binder.callingUid = secondUserSystemUid;
3959 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003960
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003961 // Device owner changes IME for first user again.
3962 mContext.binder.callingUid = deviceOwnerUid;
3963 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003964 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003965 dpm.setSecureSetting(admin1, currentIme, "ime3");
3966 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003967 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003968 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3969 mContext.binder.callingUid = firstUserSystemUid;
3970 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3971 mContext.binder.callingUid = secondUserSystemUid;
3972 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003973
3974 // Restarting the DPMS should not lose information.
3975 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003976 mContext.binder.callingUid = firstUserSystemUid;
3977 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3978 mContext.binder.callingUid = secondUserSystemUid;
3979 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003980
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003981 // Device owner can find out whether it set the current IME itself.
3982 mContext.binder.callingUid = deviceOwnerUid;
3983 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003984
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003985 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003986 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003987 mContext.binder.callingUid = firstUserSystemUid;
3988 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3989 mContext.binder.callingUid = secondUserSystemUid;
3990 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003991 }
3992
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003993 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3994 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3995 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3996 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3997 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3998 DpmMockContext.SYSTEM_UID);
3999 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
4000 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004001
4002 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004003 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004004 setupProfileOwner();
4005
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004006 // First and second user set IMEs manually.
4007 mContext.binder.callingUid = firstUserSystemUid;
4008 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4009 mContext.binder.callingUid = secondUserSystemUid;
4010 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004011
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004012 // Profile owner changes IME for second user.
4013 mContext.binder.callingUid = profileOwnerUid;
4014 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004015 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004016 dpm.setSecureSetting(admin1, currentIme, "ime2");
4017 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004018 DpmMockContext.CALLER_USER_HANDLE);
4019 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004020 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4021 mContext.binder.callingUid = firstUserSystemUid;
4022 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4023 mContext.binder.callingUid = secondUserSystemUid;
4024 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004025
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004026 // First user changes IME manually.
4027 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
4028 mContext.binder.callingUid = firstUserSystemUid;
4029 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4030 mContext.binder.callingUid = secondUserSystemUid;
4031 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004032
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004033 // Second user changes IME manually.
4034 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4035 mContext.binder.callingUid = firstUserSystemUid;
4036 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4037 mContext.binder.callingUid = secondUserSystemUid;
4038 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004039
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004040 // Profile owner changes IME for second user again.
4041 mContext.binder.callingUid = profileOwnerUid;
4042 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004043 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004044 dpm.setSecureSetting(admin1, currentIme, "ime3");
4045 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004046 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004047 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
4048 mContext.binder.callingUid = firstUserSystemUid;
4049 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4050 mContext.binder.callingUid = secondUserSystemUid;
4051 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004052
4053 // Restarting the DPMS should not lose information.
4054 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004055 mContext.binder.callingUid = firstUserSystemUid;
4056 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4057 mContext.binder.callingUid = secondUserSystemUid;
4058 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004059
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004060 // Profile owner can find out whether it set the current IME itself.
4061 mContext.binder.callingUid = profileOwnerUid;
4062 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004063
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004064 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004065 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01004066 mContext.binder.callingUid = firstUserSystemUid;
4067 assertFalse(dpm.isCurrentInputMethodSetByOwner());
4068 mContext.binder.callingUid = secondUserSystemUid;
4069 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01004070 }
Rubin Xuaab7a412016-12-30 21:13:29 +00004071
Esteban Talavera7e4cbad2017-03-30 17:59:50 +01004072 public void testSetPermittedCrossProfileNotificationListeners_unavailableForDo()
4073 throws Exception {
4074 // Set up a device owner.
4075 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4076 setupDeviceOwner();
4077 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4078 }
4079
4080 public void testSetPermittedCrossProfileNotificationListeners_unavailableForPoOnUser()
4081 throws Exception {
4082 // Set up a profile owner.
4083 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
4084 setupProfileOwner();
4085 assertSetPermittedCrossProfileNotificationListenersUnavailable(mContext.binder.callingUid);
4086 }
4087
4088 private void assertSetPermittedCrossProfileNotificationListenersUnavailable(
4089 int adminUid) throws Exception {
4090 mContext.binder.callingUid = adminUid;
4091 final int userId = UserHandle.getUserId(adminUid);
4092
4093 final String packageName = "some.package";
4094 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4095 admin1, Collections.singletonList(packageName)));
4096 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4097
4098 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4099 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4100
4101 // Attempt to set to empty list (which means no listener is whitelisted)
4102 mContext.binder.callingUid = adminUid;
4103 assertFalse(dpms.setPermittedCrossProfileNotificationListeners(
4104 admin1, Collections.<String>emptyList()));
4105 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4106
4107 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4108 assertTrue(dpms.isNotificationListenerServicePermitted(packageName, userId));
4109 }
4110
4111 public void testIsNotificationListenerServicePermitted_onlySystemCanCall() throws Exception {
4112 // Set up a managed profile
4113 final int MANAGED_PROFILE_USER_ID = 15;
4114 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4115 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4116 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4117
4118 final String permittedListener = "some.package";
4119 setupPackageInPackageManager(
4120 permittedListener,
4121 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4122 /*appId=*/ 12345, /*flags=*/ 0);
4123
4124 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4125 admin1, Collections.singletonList(permittedListener)));
4126
4127 try {
4128 dpms.isNotificationListenerServicePermitted(
4129 permittedListener, MANAGED_PROFILE_USER_ID);
4130 fail("isNotificationListenerServicePermitted should throw if not called from System");
4131 } catch (SecurityException expected) {
4132 }
4133
4134 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4135 assertTrue(dpms.isNotificationListenerServicePermitted(
4136 permittedListener, MANAGED_PROFILE_USER_ID));
4137 }
4138
4139 public void testSetPermittedCrossProfileNotificationListeners_managedProfile()
4140 throws Exception {
4141 // Set up a managed profile
4142 final int MANAGED_PROFILE_USER_ID = 15;
4143 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4144 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4145 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4146
4147 final String permittedListener = "permitted.package";
4148 int appId = 12345;
4149 setupPackageInPackageManager(
4150 permittedListener,
4151 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4152 appId, /*flags=*/ 0);
4153
4154 final String notPermittedListener = "not.permitted.package";
4155 setupPackageInPackageManager(
4156 notPermittedListener,
4157 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4158 ++appId, /*flags=*/ 0);
4159
4160 final String systemListener = "system.package";
4161 setupPackageInPackageManager(
4162 systemListener,
4163 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4164 ++appId, ApplicationInfo.FLAG_SYSTEM);
4165
4166 // By default all packages are allowed
4167 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4168
4169 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4170 assertTrue(dpms.isNotificationListenerServicePermitted(
4171 permittedListener, MANAGED_PROFILE_USER_ID));
4172 assertTrue(dpms.isNotificationListenerServicePermitted(
4173 notPermittedListener, MANAGED_PROFILE_USER_ID));
4174 assertTrue(dpms.isNotificationListenerServicePermitted(
4175 systemListener, MANAGED_PROFILE_USER_ID));
4176
4177 // Setting only one package in the whitelist
4178 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4179 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4180 admin1, Collections.singletonList(permittedListener)));
4181 List<String> permittedListeners =
4182 dpms.getPermittedCrossProfileNotificationListeners(admin1);
4183 assertEquals(1, permittedListeners.size());
4184 assertEquals(permittedListener, permittedListeners.get(0));
4185
4186 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4187 assertTrue(dpms.isNotificationListenerServicePermitted(
4188 permittedListener, MANAGED_PROFILE_USER_ID));
4189 assertFalse(dpms.isNotificationListenerServicePermitted(
4190 notPermittedListener, MANAGED_PROFILE_USER_ID));
4191 // System packages are always allowed (even if not in the whitelist)
4192 assertTrue(dpms.isNotificationListenerServicePermitted(
4193 systemListener, MANAGED_PROFILE_USER_ID));
4194
4195 // Setting an empty whitelist - only system listeners allowed
4196 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4197 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4198 admin1, Collections.<String>emptyList()));
4199 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4200
4201 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4202 assertFalse(dpms.isNotificationListenerServicePermitted(
4203 permittedListener, MANAGED_PROFILE_USER_ID));
4204 assertFalse(dpms.isNotificationListenerServicePermitted(
4205 notPermittedListener, MANAGED_PROFILE_USER_ID));
4206 // System packages are always allowed (even if not in the whitelist)
4207 assertTrue(dpms.isNotificationListenerServicePermitted(
4208 systemListener, MANAGED_PROFILE_USER_ID));
4209
4210 // Setting a null whitelist - all listeners allowed
4211 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4212 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(admin1, null));
4213 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4214
4215 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4216 assertTrue(dpms.isNotificationListenerServicePermitted(
4217 permittedListener, MANAGED_PROFILE_USER_ID));
4218 assertTrue(dpms.isNotificationListenerServicePermitted(
4219 notPermittedListener, MANAGED_PROFILE_USER_ID));
4220 assertTrue(dpms.isNotificationListenerServicePermitted(
4221 systemListener, MANAGED_PROFILE_USER_ID));
4222 }
4223
4224 public void testSetPermittedCrossProfileNotificationListeners_doesNotAffectPrimaryProfile()
4225 throws Exception {
4226 // Set up a managed profile
4227 final int MANAGED_PROFILE_USER_ID = 15;
4228 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
4229 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
4230 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4231
4232 final String nonSystemPackage = "non.system.package";
4233 int appId = 12345;
4234 setupPackageInPackageManager(
4235 nonSystemPackage,
4236 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4237 appId, /*flags=*/ 0);
4238
4239 final String systemListener = "system.package";
4240 setupPackageInPackageManager(
4241 systemListener,
4242 UserHandle.USER_SYSTEM, // We check the packageInfo from the primary user.
4243 ++appId, ApplicationInfo.FLAG_SYSTEM);
4244
4245 // By default all packages are allowed (for all profiles)
4246 assertNull(dpms.getPermittedCrossProfileNotificationListeners(admin1));
4247
4248 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4249 assertTrue(dpms.isNotificationListenerServicePermitted(
4250 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4251 assertTrue(dpms.isNotificationListenerServicePermitted(
4252 systemListener, MANAGED_PROFILE_USER_ID));
4253 assertTrue(dpms.isNotificationListenerServicePermitted(
4254 nonSystemPackage, UserHandle.USER_SYSTEM));
4255 assertTrue(dpms.isNotificationListenerServicePermitted(
4256 systemListener, UserHandle.USER_SYSTEM));
4257
4258 // Setting an empty whitelist - only system listeners allowed in managed profile, but
4259 // all allowed in primary profile
4260 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
4261 assertTrue(dpms.setPermittedCrossProfileNotificationListeners(
4262 admin1, Collections.<String>emptyList()));
4263 assertEquals(0, dpms.getPermittedCrossProfileNotificationListeners(admin1).size());
4264
4265 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4266 assertFalse(dpms.isNotificationListenerServicePermitted(
4267 nonSystemPackage, MANAGED_PROFILE_USER_ID));
4268 assertTrue(dpms.isNotificationListenerServicePermitted(
4269 systemListener, MANAGED_PROFILE_USER_ID));
4270 assertTrue(dpms.isNotificationListenerServicePermitted(
4271 nonSystemPackage, UserHandle.USER_SYSTEM));
4272 assertTrue(dpms.isNotificationListenerServicePermitted(
4273 systemListener, UserHandle.USER_SYSTEM));
4274 }
4275
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004276 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004277 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004278 setDeviceOwner();
4279
Robin Lee2c68dad2017-03-17 12:50:24 +00004280 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
4281 caller.packageName = admin1.getPackageName();
4282 caller.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
4283
4284 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004285 }
4286
4287 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004288 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004289 setAsProfileOwner(admin1);
4290
Robin Lee2c68dad2017-03-17 12:50:24 +00004291 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
4292 caller.packageName = admin1.getPackageName();
4293 caller.binder.callingUid = DpmMockContext.CALLER_UID;
4294
4295 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
4296 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004297 }
4298
4299 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004300 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004301 setAsProfileOwner(admin1);
4302
4303 final String delegate = "com.example.delegate";
4304 final int delegateUid = setupPackageInPackageManager(delegate, 20988);
4305 dpm.setCertInstallerPackage(admin1, delegate);
4306
Robin Lee2c68dad2017-03-17 12:50:24 +00004307 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
4308 caller.packageName = delegate;
4309 caller.binder.callingUid = delegateUid;
4310
4311 verifyCanGetOwnerInstalledCaCerts(null, caller);
4312 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004313 }
4314
Robin Lee2c68dad2017-03-17 12:50:24 +00004315 private void verifyCanGetOwnerInstalledCaCerts(
4316 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004317 final String alias = "cert";
4318 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004319
4320 // device admin (used for posting the tls notification)
4321 final DpmMockContext admin1Context;
4322 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4323 admin1Context = callerContext;
4324 } else {
4325 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4326 admin1Context.packageName = admin1.getPackageName();
4327 admin1Context.applicationInfo = new ApplicationInfo();
4328 }
4329 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4330
4331 // caller: device admin or delegated certificate installer
4332 callerContext.applicationInfo = new ApplicationInfo();
4333 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4334
4335 // system_server
4336 final DpmMockContext serviceContext = mContext;
4337 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4338 serviceContext.addPackageContext(callerUser, admin1Context);
4339 serviceContext.addPackageContext(callerUser, callerContext);
4340
4341 // Install a CA cert.
4342 runAsCaller(callerContext, dpms, (dpm) -> {
4343 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4344 .thenReturn(alias);
4345 assertTrue(dpm.installCaCert(caller, caCert));
4346 when(mContext.keyChainConnection.getService().getUserCaAliases())
4347 .thenReturn(asSlice(new String[] {alias}));
4348
4349 });
4350
4351 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4352 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004353 flushTasks();
4354
Robin Lee2c68dad2017-03-17 12:50:24 +00004355 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4356
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004357 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004358 runAsCaller(admin1Context, dpms, (dpm) -> {
4359 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4360 assertEquals(Arrays.asList(alias), installedCaCerts);
4361 ownerInstalledCaCerts.addAll(installedCaCerts);
4362 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004363
4364 // Restarting the DPMS should not lose information.
4365 initializeDpms();
Robin Lee2c68dad2017-03-17 12:50:24 +00004366 runAsCaller(admin1Context, dpms, (dpm) -> {
4367 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
4368 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004369
4370 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004371 runAsCaller(serviceContext, dpms, (dpm) -> {
4372 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004373
Robin Lee2c68dad2017-03-17 12:50:24 +00004374 // Remove the CA cert.
4375 reset(mContext.keyChainConnection.getService());
4376 });
4377
4378 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4379 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004380 flushTasks();
4381
4382 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4383 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004384 runAsCaller(admin1Context, dpms, (dpm) -> {
4385 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4386 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004387 }
4388
Robin Lee2c68dad2017-03-17 12:50:24 +00004389 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4390 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004391 final String alias = "cert";
4392 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004393
4394 // device admin (used for posting the tls notification)
4395 final DpmMockContext admin1Context;
4396 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4397 admin1Context = callerContext;
4398 } else {
4399 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4400 admin1Context.packageName = admin1.getPackageName();
4401 admin1Context.applicationInfo = new ApplicationInfo();
4402 }
4403 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4404
4405 // caller: device admin or delegated certificate installer
4406 callerContext.applicationInfo = new ApplicationInfo();
4407 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4408
4409 // system_server
4410 final DpmMockContext serviceContext = mContext;
4411 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4412 serviceContext.addPackageContext(callerUser, admin1Context);
4413 serviceContext.addPackageContext(callerUser, callerContext);
4414
4415 // Install a CA cert as caller
4416 runAsCaller(callerContext, dpms, (dpm) -> {
4417 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4418 .thenReturn(alias);
4419 assertTrue(dpm.installCaCert(callerName, caCert));
4420 });
4421
4422 // Fake the CA cert as having been installed
4423 when(serviceContext.keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004424 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004425 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4426 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004427 flushTasks();
4428
Robin Lee2c68dad2017-03-17 12:50:24 +00004429 // Removing the Profile Owner should clear the information on which CA certs were installed
4430 runAsCaller(admin1Context, dpms, (dpm) -> {
4431 dpm.clearProfileOwner(admin1);
4432 });
4433
4434 runAsCaller(serviceContext, dpms, (dpm) -> {
4435 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4436 assertNotNull(ownerInstalledCaCerts);
4437 assertTrue(ownerInstalledCaCerts.isEmpty());
4438 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004439 }
4440
Victor Chang3e794af2016-03-04 13:48:17 +00004441 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4442 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4443 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4444 dpms.notifyChangeToContentObserver(
4445 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4446 }
4447
4448 private void assertProvisioningAllowed(String action, boolean expected) {
4449 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4450 dpm.isProvisioningAllowed(action));
4451 }
Tony Mak2f26b792016-11-28 17:54:51 +00004452
Nicolas Prevot45d29072017-01-18 16:11:19 +00004453 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4454 int uid) {
4455 String previousPackageName = mContext.packageName;
4456 int previousUid = mMockContext.binder.callingUid;
4457
4458 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4459 mContext.packageName = packageName;
4460 mMockContext.binder.callingUid = uid;
4461 assertProvisioningAllowed(action, expected);
4462
4463 // Set the previous package name / calling uid to go back to the initial state.
4464 mContext.packageName = previousPackageName;
4465 mMockContext.binder.callingUid = previousUid;
4466 }
4467
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004468 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004469 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4470 }
4471
4472 private void assertCheckProvisioningPreCondition(
4473 String action, String packageName, int provisioningCondition) {
4474 assertEquals("checkProvisioningPreCondition("
4475 + action + ", " + packageName + ") returning unexpected result",
4476 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004477 }
4478
Tony Mak2f26b792016-11-28 17:54:51 +00004479 /**
4480 * Setup a managed profile with the specified admin and its uid.
4481 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4482 * @param adminUid uid of the admin package.
4483 * @param copyFromAdmin package information for {@code admin} will be built based on this
4484 * component's information.
4485 */
4486 private void addManagedProfile(
4487 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4488 final int userId = UserHandle.getUserId(adminUid);
4489 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4490 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4491 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4492 dpm.setActiveAdmin(admin, false, userId);
4493 assertTrue(dpm.setProfileOwner(admin, null, userId));
4494 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4495 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004496
4497 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004498 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004499 */
Robin Leeabaa0692017-02-20 20:54:22 +00004500 private static StringParceledListSlice asSlice(String[] s) {
4501 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004502 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004503
4504 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004505 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4506 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004507
Robin Lee2c68dad2017-03-17 12:50:24 +00004508 // We can't let exceptions happen on the background thread. Throw them here if they happen
4509 // so they still cause the test to fail despite being suppressed.
4510 mContext.rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004511 }
Victor Chang3e794af2016-03-04 13:48:17 +00004512}