blob: 6a01c1c6a591cbcbff3f192f979d19c62b14e3eb [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;
Makoto Onukif76b06a2015-09-22 15:03:44 -070029import android.content.BroadcastReceiver;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070030import android.content.ComponentName;
Tony Mak2f26b792016-11-28 17:54:51 +000031import android.content.Context;
32import android.content.Intent;
33import android.content.ServiceConnection;
Rubin Xued1928a2016-02-11 17:23:06 +000034import android.content.pm.ApplicationInfo;
35import android.content.pm.PackageInfo;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070036import android.content.pm.PackageManager;
Robin Leeabaa0692017-02-20 20:54:22 +000037import android.content.pm.StringParceledListSlice;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010038import android.content.res.Resources;
39import android.graphics.Color;
40import android.net.IIpConnectivityMetrics;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +010041import android.net.Uri;
Tony Mak2f26b792016-11-28 17:54:51 +000042import android.content.pm.UserInfo;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080043import android.net.wifi.WifiInfo;
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -080044import android.os.Build.VERSION_CODES;
Makoto Onukif76b06a2015-09-22 15:03:44 -070045import android.os.Bundle;
Tony Mak2f26b792016-11-28 17:54:51 +000046import android.os.IBinder;
Makoto Onukic8a5a552015-11-19 14:29:12 -080047import android.os.Process;
Makoto Onukib643fb02015-09-22 15:03:44 -070048import android.os.UserHandle;
Makoto Onukia4f11972015-10-01 13:19:58 -070049import android.os.UserManager;
Pavel Grafov6a40f092016-10-25 15:46:51 +010050import android.os.UserManagerInternal;
Makoto Onuki2a3c3da2016-02-18 14:25:30 -080051import android.provider.Settings;
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +010052import android.security.IKeyChainService;
53import android.security.KeyChain;
Mahaver Chopra1216ae52016-03-11 15:39:48 +000054import android.telephony.TelephonyManager;
Makoto Onukia31ebbc2015-11-23 17:15:21 -080055import android.test.MoreAsserts;
Benjamin Franz6d009032016-01-25 18:56:38 +000056import android.test.suitebuilder.annotation.SmallTest;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010057import android.util.ArraySet;
Makoto Onukib643fb02015-09-22 15:03:44 -070058import android.util.Pair;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070059
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010060import com.android.internal.R;
Rubin Xuaab7a412016-12-30 21:13:29 +000061import com.android.internal.widget.LockPatternUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000062import com.android.server.LocalServices;
63import com.android.server.SystemService;
Esteban Talavera6c9116a2016-11-24 16:12:44 +000064import com.android.server.pm.UserRestrictionsUtils;
Alan Treadwayafad8782016-01-19 15:15:08 +000065
Robin Lee7f5c91c2017-02-08 21:27:02 +000066import org.hamcrest.BaseMatcher;
67import org.hamcrest.Description;
Makoto Onukib643fb02015-09-22 15:03:44 -070068import org.mockito.invocation.InvocationOnMock;
69import org.mockito.stubbing.Answer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070070
Makoto Onukic8a5a552015-11-19 14:29:12 -080071import java.util.ArrayList;
Alan Treadwayafad8782016-01-19 15:15:08 +000072import java.util.Arrays;
Esteban Talaverac9bb3782016-11-11 15:41:14 +000073import java.util.Collections;
Makoto Onukib643fb02015-09-22 15:03:44 -070074import java.util.HashMap;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070075import java.util.List;
Makoto Onukib643fb02015-09-22 15:03:44 -070076import java.util.Map;
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +010077import java.util.Set;
Michal Karpinskid084ca52017-01-18 15:54:18 +000078import java.util.concurrent.TimeUnit;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070079
Edman Anjosf9946772016-11-28 16:35:15 +010080import static android.app.admin.DevicePolicyManager.DELEGATION_APP_RESTRICTIONS;
81import static android.app.admin.DevicePolicyManager.DELEGATION_CERT_INSTALL;
82
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070083import static org.mockito.Matchers.any;
Makoto Onukia52562c2015-10-01 16:12:31 -070084import static org.mockito.Matchers.anyInt;
Michal Karpinskid084ca52017-01-18 15:54:18 +000085import static org.mockito.Matchers.anyLong;
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +010086import static org.mockito.Matchers.anyObject;
Makoto Onukif76b06a2015-09-22 15:03:44 -070087import static org.mockito.Matchers.anyString;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070088import static org.mockito.Matchers.eq;
Makoto Onukif76b06a2015-09-22 15:03:44 -070089import static org.mockito.Matchers.isNull;
Esteban Talavera548a04b2016-12-20 15:22:30 +000090import static org.mockito.Mockito.atLeast;
Makoto Onukib643fb02015-09-22 15:03:44 -070091import static org.mockito.Mockito.doAnswer;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070092import static org.mockito.Mockito.doReturn;
Robin Lee7f5c91c2017-02-08 21:27:02 +000093import static org.mockito.Mockito.mock;
Robin Leed2a73ed2016-12-19 09:07:16 +000094import static org.mockito.Mockito.never;
Eric Sandnessa9b82532017-04-07 18:17:12 +010095import static org.mockito.Mockito.nullable;
Makoto Onuki1a2cd742015-11-16 13:51:27 -080096import static org.mockito.Mockito.reset;
Robin Lee7f5c91c2017-02-08 21:27:02 +000097import static org.mockito.Mockito.timeout;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -070098import static org.mockito.Mockito.times;
99import static org.mockito.Mockito.verify;
Esteban Talaverab88f42b2017-01-24 16:47:16 +0000100import static org.mockito.Mockito.verifyZeroInteractions;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700101import static org.mockito.Mockito.when;
Paul Duffin192bb0b2017-03-09 18:49:41 +0000102import static org.mockito.hamcrest.MockitoHamcrest.argThat;
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700103
104/**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700105 * Tests for DevicePolicyManager( and DevicePolicyManagerService).
Esteban Talavera01576862016-12-15 11:16:44 +0000106 * You can run them via:
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700107 m FrameworksServicesTests &&
108 adb install \
Alan Treadwayafad8782016-01-19 15:15:08 +0000109 -r ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk &&
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700110 adb shell am instrument -e class com.android.server.devicepolicy.DevicePolicyManagerTest \
Makoto Onukic8a5a552015-11-19 14:29:12 -0800111 -w com.android.frameworks.servicestests/android.support.test.runner.AndroidJUnitRunner
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700112
113 (mmma frameworks/base/services/tests/servicestests/ for non-ninja build)
Esteban Talavera01576862016-12-15 11:16:44 +0000114 *
115 * , or:
116 * runtest -c com.android.server.devicepolicy.DevicePolicyManagerTest frameworks-services
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700117 */
Benjamin Franz6d009032016-01-25 18:56:38 +0000118@SmallTest
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700119public class DevicePolicyManagerTest extends DpmTestBase {
Alan Treadwayafad8782016-01-19 15:15:08 +0000120 private static final List<String> OWNER_SETUP_PERMISSIONS = Arrays.asList(
121 permission.MANAGE_DEVICE_ADMINS, permission.MANAGE_PROFILE_AND_DEVICE_OWNERS,
122 permission.MANAGE_USERS, permission.INTERACT_ACROSS_USERS_FULL);
123
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700124 private DpmMockContext mContext;
125 public DevicePolicyManager dpm;
126 public DevicePolicyManagerServiceTestable dpms;
127
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +0100128 /*
129 * The CA cert below is the content of cacert.pem as generated by:
130 *
131 * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
132 */
133 private static final String TEST_CA =
134 "-----BEGIN CERTIFICATE-----\n" +
135 "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
136 "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
137 "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
138 "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
139 "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
140 "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
141 "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
142 "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
143 "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
144 "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
145 "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
146 "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
147 "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
148 "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
149 "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
150 "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
151 "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
152 "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
153 "wQ==\n" +
154 "-----END CERTIFICATE-----\n";
155
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700156 @Override
157 protected void setUp() throws Exception {
158 super.setUp();
159
160 mContext = getContext();
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700161 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
162 .thenReturn(true);
163
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800164 // By default, pretend all users are running and unlocked.
165 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
166
Makoto Onukia52562c2015-10-01 16:12:31 -0700167 initializeDpms();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700168
Makoto Onukid932f762015-09-29 16:53:38 -0700169 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
170 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
171 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_UID);
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800172 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700173
Makoto Onukib643fb02015-09-22 15:03:44 -0700174 setUpUserManager();
Makoto Onukif76b06a2015-09-22 15:03:44 -0700175 }
176
Robin Lee2c68dad2017-03-17 12:50:24 +0000177 @Override
178 protected void tearDown() throws Exception {
179 flushTasks();
180 super.tearDown();
181 }
182
Makoto Onukia52562c2015-10-01 16:12:31 -0700183 private void initializeDpms() {
184 // Need clearCallingIdentity() to pass permission checks.
185 final long ident = mContext.binder.clearCallingIdentity();
186 try {
187 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
188
189 dpms = new DevicePolicyManagerServiceTestable(mContext, dataDir);
190
191 dpms.systemReady(SystemService.PHASE_LOCK_SETTINGS_READY);
192 dpms.systemReady(SystemService.PHASE_BOOT_COMPLETED);
193
194 dpm = new DevicePolicyManagerTestable(mContext, dpms);
195 } finally {
196 mContext.binder.restoreCallingIdentity(ident);
197 }
198 }
199
Makoto Onukib643fb02015-09-22 15:03:44 -0700200 private void setUpUserManager() {
201 // Emulate UserManager.set/getApplicationRestriction().
202 final Map<Pair<String, UserHandle>, Bundle> appRestrictions = new HashMap<>();
203
204 // UM.setApplicationRestrictions() will save to appRestrictions.
205 doAnswer(new Answer<Void>() {
206 @Override
207 public Void answer(InvocationOnMock invocation) throws Throwable {
208 String pkg = (String) invocation.getArguments()[0];
209 Bundle bundle = (Bundle) invocation.getArguments()[1];
210 UserHandle user = (UserHandle) invocation.getArguments()[2];
211
212 appRestrictions.put(Pair.create(pkg, user), bundle);
213
214 return null;
215 }
216 }).when(mContext.userManager).setApplicationRestrictions(
Eric Sandnessa9b82532017-04-07 18:17:12 +0100217 anyString(), nullable(Bundle.class), any(UserHandle.class));
Makoto Onukib643fb02015-09-22 15:03:44 -0700218
219 // UM.getApplicationRestrictions() will read from appRestrictions.
220 doAnswer(new Answer<Bundle>() {
221 @Override
222 public Bundle answer(InvocationOnMock invocation) throws Throwable {
223 String pkg = (String) invocation.getArguments()[0];
224 UserHandle user = (UserHandle) invocation.getArguments()[1];
225
226 return appRestrictions.get(Pair.create(pkg, user));
227 }
228 }).when(mContext.userManager).getApplicationRestrictions(
229 anyString(), any(UserHandle.class));
230
Makoto Onukid932f762015-09-29 16:53:38 -0700231 // Add the first secondary user.
232 mContext.addUser(DpmMockContext.CALLER_USER_HANDLE, 0);
Makoto Onukib643fb02015-09-22 15:03:44 -0700233 }
234
235 private void setAsProfileOwner(ComponentName admin) {
236 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
237 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
238
Makoto Onukia4f11972015-10-01 13:19:58 -0700239 // PO needs to be an DA.
Makoto Onukib643fb02015-09-22 15:03:44 -0700240 dpm.setActiveAdmin(admin, /* replace =*/ false);
241
242 // Fire!
243 assertTrue(dpm.setProfileOwner(admin, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
244
245 // Check
Makoto Onuki068c54a2015-10-13 14:34:03 -0700246 assertEquals(admin, dpm.getProfileOwnerAsUser(DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukib643fb02015-09-22 15:03:44 -0700247 }
248
249 public void testHasNoFeature() throws Exception {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700250 when(mContext.packageManager.hasSystemFeature(eq(PackageManager.FEATURE_DEVICE_ADMIN)))
251 .thenReturn(false);
252
253 LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
254 new DevicePolicyManagerServiceTestable(mContext, dataDir);
255
256 // If the device has no DPMS feature, it shouldn't register the local service.
257 assertNull(LocalServices.getService(DevicePolicyManagerInternal.class));
258 }
259
260 /**
261 * Caller doesn't have proper permissions.
262 */
263 public void testSetActiveAdmin_SecurityException() {
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700264 // 1. Failure cases.
265
266 // Caller doesn't have MANAGE_DEVICE_ADMINS.
267 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700268 dpm.setActiveAdmin(admin1, false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700269 fail("Didn't throw SecurityException");
270 } catch (SecurityException expected) {
271 }
272
273 // Caller has MANAGE_DEVICE_ADMINS, but for different user.
274 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
275 try {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700276 dpm.setActiveAdmin(admin1, false, DpmMockContext.CALLER_USER_HANDLE + 1);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700277 fail("Didn't throw SecurityException");
278 } catch (SecurityException expected) {
279 }
280 }
281
Makoto Onukif76b06a2015-09-22 15:03:44 -0700282 /**
283 * Test for:
284 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800285 * with replace=false and replace=true
Makoto Onukif76b06a2015-09-22 15:03:44 -0700286 * {@link DevicePolicyManager#isAdminActive}
287 * {@link DevicePolicyManager#isAdminActiveAsUser}
288 * {@link DevicePolicyManager#getActiveAdmins}
289 * {@link DevicePolicyManager#getActiveAdminsAsUser}
290 */
291 public void testSetActiveAdmin() throws Exception {
292 // 1. Make sure the caller has proper permissions.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700293 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
294
Makoto Onukif76b06a2015-09-22 15:03:44 -0700295 // 2. Call the API.
296 dpm.setActiveAdmin(admin1, /* replace =*/ false);
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700297
298 // 3. Verify internal calls.
299
300 // Check if the boradcast is sent.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700301 verify(mContext.spiedContext).sendBroadcastAsUser(
302 MockUtils.checkIntentAction(
303 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
304 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
305 verify(mContext.spiedContext).sendBroadcastAsUser(
306 MockUtils.checkIntentAction(
307 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_ENABLED),
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700308 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
309
Makoto Onukif76b06a2015-09-22 15:03:44 -0700310 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
311 eq(admin1.getPackageName()),
312 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
313 eq(PackageManager.DONT_KILL_APP),
314 eq(DpmMockContext.CALLER_USER_HANDLE),
315 anyString());
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700316
317 // TODO Verify other calls too.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700318
319 // Make sure it's active admin1.
320 assertTrue(dpm.isAdminActive(admin1));
321 assertFalse(dpm.isAdminActive(admin2));
322 assertFalse(dpm.isAdminActive(admin3));
323
324 // But not admin1 for a different user.
325
326 // For this to work, caller needs android.permission.INTERACT_ACROSS_USERS_FULL.
327 // (Because we're checking a different user's status from CALLER_USER_HANDLE.)
328 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
329
330 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE + 1));
331 assertFalse(dpm.isAdminActiveAsUser(admin2, DpmMockContext.CALLER_USER_HANDLE + 1));
332
333 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
334
335 // Next, add one more admin.
336 // Before doing so, update the application info, now it's enabled.
Makoto Onukia52562c2015-10-01 16:12:31 -0700337 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID,
338 PackageManager.COMPONENT_ENABLED_STATE_ENABLED);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700339
340 dpm.setActiveAdmin(admin2, /* replace =*/ false);
341
342 // Now we have two admins.
343 assertTrue(dpm.isAdminActive(admin1));
344 assertTrue(dpm.isAdminActive(admin2));
345 assertFalse(dpm.isAdminActive(admin3));
346
347 // Admin2 was already enabled, so setApplicationEnabledSetting() shouldn't have called
348 // again. (times(1) because it was previously called for admin1)
349 verify(mContext.ipackageManager, times(1)).setApplicationEnabledSetting(
350 eq(admin1.getPackageName()),
351 eq(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT),
352 eq(PackageManager.DONT_KILL_APP),
353 eq(DpmMockContext.CALLER_USER_HANDLE),
354 anyString());
355
356 // 4. Add the same admin1 again without replace, which should throw.
357 try {
358 dpm.setActiveAdmin(admin1, /* replace =*/ false);
359 fail("Didn't throw");
360 } catch (IllegalArgumentException expected) {
361 }
362
363 // 5. Add the same admin1 again with replace, which should succeed.
364 dpm.setActiveAdmin(admin1, /* replace =*/ true);
365
366 // TODO make sure it's replaced.
367
368 // 6. Test getActiveAdmins()
369 List<ComponentName> admins = dpm.getActiveAdmins();
370 assertEquals(2, admins.size());
371 assertEquals(admin1, admins.get(0));
372 assertEquals(admin2, admins.get(1));
373
374 // Another user has no admins.
375 mContext.callerPermissions.add("android.permission.INTERACT_ACROSS_USERS_FULL");
376
377 assertEquals(0, DpmTestUtils.getListSizeAllowingNull(
378 dpm.getActiveAdminsAsUser(DpmMockContext.CALLER_USER_HANDLE + 1)));
379
380 mContext.callerPermissions.remove("android.permission.INTERACT_ACROSS_USERS_FULL");
381 }
382
Makoto Onukid932f762015-09-29 16:53:38 -0700383 public void testSetActiveAdmin_multiUsers() throws Exception {
384
385 final int ANOTHER_USER_ID = 100;
386 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 20456);
387
388 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
389
390 // Set up pacakge manager for the other user.
391 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700392
393 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
394
395 dpm.setActiveAdmin(admin1, /* replace =*/ false);
396
397 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
398 dpm.setActiveAdmin(admin2, /* replace =*/ false);
399
400
401 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
402 assertTrue(dpm.isAdminActive(admin1));
403 assertFalse(dpm.isAdminActive(admin2));
404
405 mMockContext.binder.callingUid = ANOTHER_ADMIN_UID;
406 assertFalse(dpm.isAdminActive(admin1));
407 assertTrue(dpm.isAdminActive(admin2));
408 }
409
Makoto Onukif76b06a2015-09-22 15:03:44 -0700410 /**
411 * Test for:
412 * {@link DevicePolicyManager#setActiveAdmin}
Makoto Onuki2a3c3da2016-02-18 14:25:30 -0800413 * with replace=false
Makoto Onukif76b06a2015-09-22 15:03:44 -0700414 */
415 public void testSetActiveAdmin_twiceWithoutReplace() throws Exception {
416 // 1. Make sure the caller has proper permissions.
417 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
418
419 dpm.setActiveAdmin(admin1, /* replace =*/ false);
420 assertTrue(dpm.isAdminActive(admin1));
421
422 // Add the same admin1 again without replace, which should throw.
423 try {
424 dpm.setActiveAdmin(admin1, /* replace =*/ false);
425 fail("Didn't throw");
426 } catch (IllegalArgumentException expected) {
427 }
428 }
429
430 /**
431 * Test for:
Makoto Onuki3ab6f2e2015-11-05 13:55:37 -0800432 * {@link DevicePolicyManager#setActiveAdmin} when the admin isn't protected with
433 * BIND_DEVICE_ADMIN.
434 */
435 public void testSetActiveAdmin_permissionCheck() throws Exception {
436 // 1. Make sure the caller has proper permissions.
437 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
438
439 try {
440 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
441 fail();
442 } catch (IllegalArgumentException expected) {
443 assertTrue(expected.getMessage().contains(permission.BIND_DEVICE_ADMIN));
444 }
445 assertFalse(dpm.isAdminActive(adminNoPerm));
446
447 // Change the target API level to MNC. Now it can be set as DA.
448 setUpPackageManagerForAdmin(adminNoPerm, DpmMockContext.CALLER_UID, null,
449 VERSION_CODES.M);
450 dpm.setActiveAdmin(adminNoPerm, /* replace =*/ false);
451 assertTrue(dpm.isAdminActive(adminNoPerm));
452
453 // TODO Test the "load from the file" case where DA will still be loaded even without
454 // BIND_DEVICE_ADMIN and target API is N.
455 }
456
457 /**
458 * Test for:
Makoto Onukif76b06a2015-09-22 15:03:44 -0700459 * {@link DevicePolicyManager#removeActiveAdmin}
460 */
461 public void testRemoveActiveAdmin_SecurityException() {
462 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
463
464 // Add admin.
465
466 dpm.setActiveAdmin(admin1, /* replace =*/ false);
467
468 assertTrue(dpm.isAdminActive(admin1));
469
470 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
471
472 // Directly call the DPMS method with a different userid, which should fail.
473 try {
474 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE + 1);
475 fail("Didn't throw SecurityException");
476 } catch (SecurityException expected) {
477 }
478
479 // Try to remove active admin with a different caller userid should fail too, without
480 // having MANAGE_DEVICE_ADMINS.
481 mContext.callerPermissions.clear();
482
Makoto Onukid932f762015-09-29 16:53:38 -0700483 // Change the caller, and call into DPMS directly with a different user-id.
484
Makoto Onukif76b06a2015-09-22 15:03:44 -0700485 mContext.binder.callingUid = 1234567;
486 try {
Makoto Onukid932f762015-09-29 16:53:38 -0700487 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Makoto Onukif76b06a2015-09-22 15:03:44 -0700488 fail("Didn't throw SecurityException");
489 } catch (SecurityException expected) {
490 }
491 }
492
493 /**
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800494 * {@link DevicePolicyManager#removeActiveAdmin} should fail with the user is not unlocked
495 * (because we can't send the remove broadcast).
496 */
497 public void testRemoveActiveAdmin_userNotRunningOrLocked() {
498 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
499
500 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
501
502 // Add admin.
503
504 dpm.setActiveAdmin(admin1, /* replace =*/ false);
505
506 assertTrue(dpm.isAdminActive(admin1));
507
508 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
509
510 // 1. User not unlocked.
511 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
512 .thenReturn(false);
513 try {
514 dpm.removeActiveAdmin(admin1);
515 fail("Didn't throw IllegalStateException");
516 } catch (IllegalStateException expected) {
517 MoreAsserts.assertContainsRegex(
518 "User must be running and unlocked", expected.getMessage());
519 }
520
521 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
522
523 // 2. User unlocked.
524 when(mContext.userManager.isUserUnlocked(eq(DpmMockContext.CALLER_USER_HANDLE)))
525 .thenReturn(true);
526
527 dpm.removeActiveAdmin(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700528 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800529 }
530
531 /**
Makoto Onukif76b06a2015-09-22 15:03:44 -0700532 * Test for:
533 * {@link DevicePolicyManager#removeActiveAdmin}
534 */
Makoto Onukid932f762015-09-29 16:53:38 -0700535 public void testRemoveActiveAdmin_fromDifferentUserWithINTERACT_ACROSS_USERS_FULL() {
Makoto Onukif76b06a2015-09-22 15:03:44 -0700536 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
537
538 // Add admin1.
539
540 dpm.setActiveAdmin(admin1, /* replace =*/ false);
541
542 assertTrue(dpm.isAdminActive(admin1));
543 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
544
545 // Different user, but should work, because caller has proper permissions.
546 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
Makoto Onukid932f762015-09-29 16:53:38 -0700547
548 // Change the caller, and call into DPMS directly with a different user-id.
Makoto Onukif76b06a2015-09-22 15:03:44 -0700549 mContext.binder.callingUid = 1234567;
Makoto Onukid932f762015-09-29 16:53:38 -0700550
551 dpms.removeActiveAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700552 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700553
554 // TODO DO Still can't be removed in this case.
555 }
556
557 /**
558 * Test for:
559 * {@link DevicePolicyManager#removeActiveAdmin}
560 */
561 public void testRemoveActiveAdmin_sameUserNoMANAGE_DEVICE_ADMINS() {
562 // Need MANAGE_DEVICE_ADMINS for setActiveAdmin. We'll remove it later.
563 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
564
565 // Add admin1.
566
567 dpm.setActiveAdmin(admin1, /* replace =*/ false);
568
569 assertTrue(dpm.isAdminActive(admin1));
570 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
571
572 // Broadcast from saveSettingsLocked().
573 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
574 MockUtils.checkIntentAction(
575 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
576 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
577
578 // Remove. No permissions, but same user, so it'll work.
579 mContext.callerPermissions.clear();
580 dpm.removeActiveAdmin(admin1);
581
Makoto Onukif76b06a2015-09-22 15:03:44 -0700582 verify(mContext.spiedContext).sendOrderedBroadcastAsUser(
583 MockUtils.checkIntentAction(
584 DeviceAdminReceiver.ACTION_DEVICE_ADMIN_DISABLED),
585 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE),
586 isNull(String.class),
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700587 any(BroadcastReceiver.class),
Makoto Onukif76b06a2015-09-22 15:03:44 -0700588 eq(dpms.mHandler),
589 eq(Activity.RESULT_OK),
590 isNull(String.class),
591 isNull(Bundle.class));
592
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700593 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onukif76b06a2015-09-22 15:03:44 -0700594
595 // Again broadcast from saveSettingsLocked().
596 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
597 MockUtils.checkIntentAction(
598 DevicePolicyManager.ACTION_DEVICE_POLICY_MANAGER_STATE_CHANGED),
599 MockUtils.checkUserHandle(DpmMockContext.CALLER_USER_HANDLE));
600
601 // TODO Check other internal calls.
Makoto Onukicc4bbeb2015-09-17 10:28:24 -0700602 }
Makoto Onukib643fb02015-09-22 15:03:44 -0700603
604 /**
Robin Leed2a73ed2016-12-19 09:07:16 +0000605 * Test for: @{link DevicePolicyManager#setActivePasswordState}
606 *
607 * Validates that when the password for a user changes, the notification broadcast intent
608 * {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is sent to managed profile owners, in
609 * addition to ones in the original user.
610 */
611 public void testSetActivePasswordState_sendToProfiles() throws Exception {
612 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
613
614 final int MANAGED_PROFILE_USER_ID = 78;
615 final int MANAGED_PROFILE_ADMIN_UID =
616 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
617
618 // Setup device owner.
619 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
620 mContext.packageName = admin1.getPackageName();
621 setupDeviceOwner();
622
623 // Add a managed profile belonging to the system user.
624 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
625
626 // Change the parent user's password.
627 dpm.reportPasswordChanged(UserHandle.USER_SYSTEM);
628
629 // Both the device owner and the managed profile owner should receive this broadcast.
630 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
631 intent.setComponent(admin1);
632 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(UserHandle.USER_SYSTEM));
633
634 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
635 MockUtils.checkIntent(intent),
636 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
637 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
638 MockUtils.checkIntent(intent),
639 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
640 }
641
642 /**
643 * Test for: @{link DevicePolicyManager#setActivePasswordState}
644 *
645 * Validates that when the password for a managed profile changes, the notification broadcast
646 * intent {@link DeviceAdminReceiver#ACTION_PASSWORD_CHANGED} is only sent to the profile, not
647 * its parent.
648 */
649 public void testSetActivePasswordState_notSentToParent() throws Exception {
650 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
651
652 final int MANAGED_PROFILE_USER_ID = 78;
653 final int MANAGED_PROFILE_ADMIN_UID =
654 UserHandle.getUid(MANAGED_PROFILE_USER_ID, DpmMockContext.SYSTEM_UID);
655
656 // Setup device owner.
657 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
658 mContext.packageName = admin1.getPackageName();
659 doReturn(true).when(mContext.lockPatternUtils)
660 .isSeparateProfileChallengeEnabled(MANAGED_PROFILE_USER_ID);
661 setupDeviceOwner();
662
663 // Add a managed profile belonging to the system user.
664 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
665
666 // Change the profile's password.
667 dpm.reportPasswordChanged(MANAGED_PROFILE_USER_ID);
668
669 // Both the device owner and the managed profile owner should receive this broadcast.
670 final Intent intent = new Intent(DeviceAdminReceiver.ACTION_PASSWORD_CHANGED);
671 intent.setComponent(admin1);
672 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(MANAGED_PROFILE_USER_ID));
673
674 verify(mContext.spiedContext, never()).sendBroadcastAsUser(
675 MockUtils.checkIntent(intent),
676 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
677 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
678 MockUtils.checkIntent(intent),
679 MockUtils.checkUserHandle(MANAGED_PROFILE_USER_ID));
680 }
681 /**
Victor Chang3e794af2016-03-04 13:48:17 +0000682 * Test for: {@link DevicePolicyManager#setDeviceOwner} DO on system user installs successfully.
Makoto Onukib643fb02015-09-22 15:03:44 -0700683 */
684 public void testSetDeviceOwner() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +0000685 setDeviceOwner();
686
687 // Try to set a profile owner on the same user, which should fail.
688 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
689 dpm.setActiveAdmin(admin2, /* refreshing= */ true, UserHandle.USER_SYSTEM);
690 try {
691 dpm.setProfileOwner(admin2, "owner-name", UserHandle.USER_SYSTEM);
692 fail("IllegalStateException not thrown");
693 } catch (IllegalStateException expected) {
694 assertTrue("Message was: " + expected.getMessage(),
695 expected.getMessage().contains("already has a device owner"));
696 }
697
698 // DO admin can't be deactivated.
699 dpm.removeActiveAdmin(admin1);
700 assertTrue(dpm.isAdminActive(admin1));
701
702 // TODO Test getDeviceOwnerName() too. To do so, we need to change
703 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
704 }
705
706 private void setDeviceOwner() throws Exception {
Makoto Onukib643fb02015-09-22 15:03:44 -0700707 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800708 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700709 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
710 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
711
Makoto Onukid932f762015-09-29 16:53:38 -0700712 // In this test, change the caller user to "system".
Makoto Onukib643fb02015-09-22 15:03:44 -0700713 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
714
Makoto Onukid932f762015-09-29 16:53:38 -0700715 // Make sure admin1 is installed on system user.
716 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukid932f762015-09-29 16:53:38 -0700717
Makoto Onukic8a5a552015-11-19 14:29:12 -0800718 // Check various get APIs.
719 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ false);
720
Makoto Onukib643fb02015-09-22 15:03:44 -0700721 // DO needs to be an DA.
722 dpm.setActiveAdmin(admin1, /* replace =*/ false);
723
724 // Fire!
Makoto Onukia52562c2015-10-01 16:12:31 -0700725 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700726
Makoto Onukic8a5a552015-11-19 14:29:12 -0800727 // getDeviceOwnerComponent should return the admin1 component.
728 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
729 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
730
731 // Check various get APIs.
732 checkGetDeviceOwnerInfoApi(dpm, /* hasDeviceOwner =*/ true);
733
734 // getDeviceOwnerComponent should *NOT* return the admin1 component for other users.
735 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
736 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
737 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
738
739 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
740
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000741 // Verify internal calls.
742 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
743 eq(admin1.getPackageName()));
744
Makoto Onukib643fb02015-09-22 15:03:44 -0700745 // TODO We should check if the caller has called clearCallerIdentity().
746 verify(mContext.ibackupManager, times(1)).setBackupServiceActive(
747 eq(UserHandle.USER_SYSTEM), eq(false));
748
749 verify(mContext.spiedContext, times(1)).sendBroadcastAsUser(
750 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
751 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
752
Makoto Onukic8a5a552015-11-19 14:29:12 -0800753 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukib643fb02015-09-22 15:03:44 -0700754 }
755
Makoto Onukic8a5a552015-11-19 14:29:12 -0800756 private void checkGetDeviceOwnerInfoApi(DevicePolicyManager dpm, boolean hasDeviceOwner) {
757 final int origCallingUser = mContext.binder.callingUid;
758 final List origPermissions = new ArrayList(mContext.callerPermissions);
759 mContext.callerPermissions.clear();
760
761 mContext.callerPermissions.add(permission.MANAGE_USERS);
762
763 mContext.binder.callingUid = Process.SYSTEM_UID;
764
765 // TODO Test getDeviceOwnerName() too. To do so, we need to change
766 // DPMS.getApplicationLabel() because Context.createPackageContextAsUser() is not mockable.
767 if (hasDeviceOwner) {
768 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
769 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
770 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
771
772 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
773 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
774 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
775 } else {
776 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
777 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
778 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
779
780 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
781 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
782 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
783 }
784
785 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
786 if (hasDeviceOwner) {
787 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
788 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
789 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
790
791 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
792 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
793 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
794 } else {
795 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
796 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
797 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
798
799 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
800 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
801 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
802 }
803
804 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
805 // Still with MANAGE_USERS.
806 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
807 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
808 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
809
810 if (hasDeviceOwner) {
811 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
812 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
813 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
814 } else {
815 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
816 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
817 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
818 }
819
820 mContext.binder.callingUid = Process.SYSTEM_UID;
821 mContext.callerPermissions.remove(permission.MANAGE_USERS);
822 // System can still call "OnAnyUser" without MANAGE_USERS.
823 if (hasDeviceOwner) {
824 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
825 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
826 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
827
828 assertTrue(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
829 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
830 assertEquals(UserHandle.USER_SYSTEM, dpm.getDeviceOwnerUserId());
831 } else {
832 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
833 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
834 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
835
836 assertFalse(dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName()));
837 assertEquals(null, dpm.getDeviceOwnerComponentOnAnyUser());
838 assertEquals(UserHandle.USER_NULL, dpm.getDeviceOwnerUserId());
839 }
840
841 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
842 // Still no MANAGE_USERS.
843 if (hasDeviceOwner) {
844 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
845 assertTrue(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
846 assertEquals(admin1, dpm.getDeviceOwnerComponentOnCallingUser());
847 } else {
848 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
849 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
850 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
851 }
852
853 try {
854 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
855 fail();
856 } catch (SecurityException expected) {
857 }
858 try {
859 dpm.getDeviceOwnerComponentOnAnyUser();
860 fail();
861 } catch (SecurityException expected) {
862 }
863 try {
864 dpm.getDeviceOwnerUserId();
865 fail();
866 } catch (SecurityException expected) {
867 }
868 try {
869 dpm.getDeviceOwnerNameOnAnyUser();
870 fail();
871 } catch (SecurityException expected) {
872 }
873
874 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
875 // Still no MANAGE_USERS.
876 assertFalse(dpm.isDeviceOwnerApp(admin1.getPackageName()));
877 assertFalse(dpm.isDeviceOwnerAppOnCallingUser(admin1.getPackageName()));
878 assertEquals(null, dpm.getDeviceOwnerComponentOnCallingUser());
879
880 try {
881 dpm.isDeviceOwnerAppOnAnyUser(admin1.getPackageName());
882 fail();
883 } catch (SecurityException expected) {
884 }
885 try {
886 dpm.getDeviceOwnerComponentOnAnyUser();
887 fail();
888 } catch (SecurityException expected) {
889 }
890 try {
891 dpm.getDeviceOwnerUserId();
892 fail();
893 } catch (SecurityException expected) {
894 }
895 try {
896 dpm.getDeviceOwnerNameOnAnyUser();
897 fail();
898 } catch (SecurityException expected) {
899 }
900
901 // Restore.
902 mContext.binder.callingUid = origCallingUser;
903 mContext.callerPermissions.addAll(origPermissions);
904 }
905
906
Makoto Onukib643fb02015-09-22 15:03:44 -0700907 /**
908 * Test for: {@link DevicePolicyManager#setDeviceOwner} Package doesn't exist.
909 */
910 public void testSetDeviceOwner_noSuchPackage() {
911 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800912 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukib643fb02015-09-22 15:03:44 -0700913 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
914 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
915
916 // Call from a process on the system user.
917 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
918
Makoto Onukib643fb02015-09-22 15:03:44 -0700919 try {
Makoto Onukia52562c2015-10-01 16:12:31 -0700920 dpm.setDeviceOwner(new ComponentName("a.b.c", ".def"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700921 fail("Didn't throw IllegalArgumentException");
922 } catch (IllegalArgumentException expected) {
Makoto Onuki803d6752015-10-30 12:58:39 -0700923 assertTrue("Message was: " + expected.getMessage(),
924 expected.getMessage().contains("Invalid component"));
Makoto Onukib643fb02015-09-22 15:03:44 -0700925 }
926 }
927
928 public void testSetDeviceOwner_failures() throws Exception {
929 // TODO Test more failure cases. Basically test all chacks in enforceCanSetDeviceOwner().
930 }
931
Makoto Onukia52562c2015-10-01 16:12:31 -0700932 public void testClearDeviceOwner() throws Exception {
933 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -0800934 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -0700935 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
936 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
937
938 // Set admin1 as a DA to the secondary user.
939 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
940
941 dpm.setActiveAdmin(admin1, /* replace =*/ false);
942
943 // Set admin 1 as the DO to the system user.
944
945 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
946 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
947 dpm.setActiveAdmin(admin1, /* replace =*/ false);
948 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
949
Makoto Onuki219bbaf2015-11-12 01:38:47 +0000950 // Verify internal calls.
951 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
952 eq(admin1.getPackageName()));
953
Makoto Onukic8a5a552015-11-19 14:29:12 -0800954 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700955
Makoto Onuki90b89652016-01-28 14:44:18 -0800956 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
Victor Chang348f6962017-01-30 16:19:13 +0000957 when(mContext.userManager.hasUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
958 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM))).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800959
960 assertTrue(dpm.isAdminActive(admin1));
961 assertFalse(dpm.isRemovingAdmin(admin1, UserHandle.USER_SYSTEM));
962
Makoto Onukia52562c2015-10-01 16:12:31 -0700963 // Set up other mocks.
964 when(mContext.userManager.getUserRestrictions()).thenReturn(new Bundle());
965
966 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700967 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -0700968 eq(admin1.getPackageName()),
969 anyInt());
Makoto Onuki1a5ee772016-02-12 15:34:57 -0800970
971 // But first pretend the user is locked. Then it should fail.
972 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(false);
973 try {
974 dpm.clearDeviceOwnerApp(admin1.getPackageName());
975 fail("Didn't throw IllegalStateException");
976 } catch (IllegalStateException expected) {
977 MoreAsserts.assertContainsRegex(
978 "User must be running and unlocked", expected.getMessage());
979 }
980
981 when(mContext.userManager.isUserUnlocked(anyInt())).thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -0800982 reset(mContext.userManagerInternal);
Makoto Onukia52562c2015-10-01 16:12:31 -0700983 dpm.clearDeviceOwnerApp(admin1.getPackageName());
984
985 // Now DO shouldn't be set.
Makoto Onukic8a5a552015-11-19 14:29:12 -0800986 assertNull(dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -0700987
Victor Chang348f6962017-01-30 16:19:13 +0000988 verify(mContext.userManager).setUserRestriction(eq(UserManager.DISALLOW_ADD_USER),
989 eq(false),
990 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
991
Makoto Onuki90b89652016-01-28 14:44:18 -0800992 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
993 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +0100994 eq(null),
995 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki90b89652016-01-28 14:44:18 -0800996
Suprabh Shukla3cb2b492016-08-09 17:20:57 -0700997 assertFalse(dpm.isAdminActiveAsUser(admin1, UserHandle.USER_SYSTEM));
Tony Mak1970f972016-08-30 17:41:48 +0100998
999 // ACTION_DEVICE_OWNER_CHANGED should be sent twice, once for setting the device owner
1000 // and once for clearing it.
1001 verify(mContext.spiedContext, times(2)).sendBroadcastAsUser(
1002 MockUtils.checkIntentAction(DevicePolicyManager.ACTION_DEVICE_OWNER_CHANGED),
1003 MockUtils.checkUserHandle(UserHandle.USER_SYSTEM));
Makoto Onukia52562c2015-10-01 16:12:31 -07001004 // TODO Check other calls.
1005 }
1006
1007 public void testClearDeviceOwner_fromDifferentUser() throws Exception {
1008 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001009 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001010 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1011 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1012
1013 // Set admin1 as a DA to the secondary user.
1014 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1015
1016 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1017
1018 // Set admin 1 as the DO to the system user.
1019
1020 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1021 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1022 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1023 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
1024
Makoto Onuki219bbaf2015-11-12 01:38:47 +00001025 // Verify internal calls.
1026 verify(mContext.iactivityManager, times(1)).updateDeviceOwner(
1027 eq(admin1.getPackageName()));
1028
Makoto Onukic8a5a552015-11-19 14:29:12 -08001029 assertEquals(admin1, dpm.getDeviceOwnerComponentOnAnyUser());
Makoto Onukia52562c2015-10-01 16:12:31 -07001030
1031 // Now call clear from the secondary user, which should throw.
1032 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1033
1034 // Now call clear.
Jeff Sharkeye06b4d12016-01-06 14:51:50 -07001035 doReturn(DpmMockContext.CALLER_UID).when(mContext.packageManager).getPackageUidAsUser(
Makoto Onukia52562c2015-10-01 16:12:31 -07001036 eq(admin1.getPackageName()),
1037 anyInt());
1038 try {
1039 dpm.clearDeviceOwnerApp(admin1.getPackageName());
1040 fail("Didn't throw");
1041 } catch (SecurityException e) {
1042 assertEquals("clearDeviceOwner can only be called by the device owner", e.getMessage());
1043 }
1044
Makoto Onukic8a5a552015-11-19 14:29:12 -08001045 // DO shouldn't be removed.
1046 assertTrue(dpm.isDeviceManaged());
Makoto Onukia52562c2015-10-01 16:12:31 -07001047 }
1048
Makoto Onukib643fb02015-09-22 15:03:44 -07001049 public void testSetProfileOwner() throws Exception {
1050 setAsProfileOwner(admin1);
Makoto Onuki803d6752015-10-30 12:58:39 -07001051
Makoto Onuki90b89652016-01-28 14:44:18 -08001052 // PO admin can't be deactivated.
1053 dpm.removeActiveAdmin(admin1);
1054 assertTrue(dpm.isAdminActive(admin1));
1055
Makoto Onuki803d6752015-10-30 12:58:39 -07001056 // Try setting DO on the same user, which should fail.
1057 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1058 dpm.setActiveAdmin(admin2, /* refreshing= */ true, DpmMockContext.CALLER_USER_HANDLE);
1059 try {
1060 dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1061 fail("IllegalStateException not thrown");
1062 } catch (IllegalStateException expected) {
1063 assertTrue("Message was: " + expected.getMessage(),
1064 expected.getMessage().contains("already has a profile owner"));
1065 }
Makoto Onukib643fb02015-09-22 15:03:44 -07001066 }
1067
Makoto Onuki90b89652016-01-28 14:44:18 -08001068 public void testClearProfileOwner() throws Exception {
1069 setAsProfileOwner(admin1);
1070
1071 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1072
1073 assertTrue(dpm.isProfileOwnerApp(admin1.getPackageName()));
1074 assertFalse(dpm.isRemovingAdmin(admin1, DpmMockContext.CALLER_USER_HANDLE));
1075
Makoto Onuki1a5ee772016-02-12 15:34:57 -08001076 // First try when the user is locked, which should fail.
1077 when(mContext.userManager.isUserUnlocked(anyInt()))
1078 .thenReturn(false);
1079 try {
1080 dpm.clearProfileOwner(admin1);
1081 fail("Didn't throw IllegalStateException");
1082 } catch (IllegalStateException expected) {
1083 MoreAsserts.assertContainsRegex(
1084 "User must be running and unlocked", expected.getMessage());
1085 }
1086 // Clear, really.
1087 when(mContext.userManager.isUserUnlocked(anyInt()))
1088 .thenReturn(true);
Makoto Onuki90b89652016-01-28 14:44:18 -08001089 dpm.clearProfileOwner(admin1);
1090
1091 // Check
1092 assertFalse(dpm.isProfileOwnerApp(admin1.getPackageName()));
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001093 assertFalse(dpm.isAdminActiveAsUser(admin1, DpmMockContext.CALLER_USER_HANDLE));
Makoto Onuki90b89652016-01-28 14:44:18 -08001094 }
1095
Makoto Onukib643fb02015-09-22 15:03:44 -07001096 public void testSetProfileOwner_failures() throws Exception {
1097 // TODO Test more failure cases. Basically test all chacks in enforceCanSetProfileOwner().
1098 }
1099
Makoto Onukia52562c2015-10-01 16:12:31 -07001100 public void testGetDeviceOwnerAdminLocked() throws Exception {
1101 checkDeviceOwnerWithMultipleDeviceAdmins();
1102 }
1103
1104 private void checkDeviceOwnerWithMultipleDeviceAdmins() throws Exception {
1105 // In ths test, we use 3 users (system + 2 secondary users), set some device admins to them,
1106 // set admin2 on CALLER_USER_HANDLE as DO, then call getDeviceOwnerAdminLocked() to
1107 // make sure it gets the right component from the right user.
1108
1109 final int ANOTHER_USER_ID = 100;
1110 final int ANOTHER_ADMIN_UID = UserHandle.getUid(ANOTHER_USER_ID, 456);
1111
1112 mMockContext.addUser(ANOTHER_USER_ID, 0); // Add one more user.
1113
1114 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001115 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia52562c2015-10-01 16:12:31 -07001116 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1117 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1118
1119 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1120
Victor Change29cd472016-03-02 20:57:42 +00001121 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
1122
Makoto Onukia52562c2015-10-01 16:12:31 -07001123 // Make sure the admin packge is installed to each user.
1124 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1125 setUpPackageManagerForAdmin(admin3, DpmMockContext.CALLER_SYSTEM_USER_UID);
1126
1127 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
1128 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_UID);
1129
1130 setUpPackageManagerForAdmin(admin2, ANOTHER_ADMIN_UID);
1131
1132
1133 // Set active admins to the users.
1134 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1135 dpm.setActiveAdmin(admin3, /* replace =*/ false);
1136
1137 dpm.setActiveAdmin(admin1, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1138 dpm.setActiveAdmin(admin2, /* replace =*/ false, DpmMockContext.CALLER_USER_HANDLE);
1139
1140 dpm.setActiveAdmin(admin2, /* replace =*/ false, ANOTHER_USER_ID);
1141
1142 // Set DO on the first non-system user.
1143 mContext.setUserRunning(DpmMockContext.CALLER_USER_HANDLE, true);
1144 assertTrue(dpm.setDeviceOwner(admin2, "owner-name", DpmMockContext.CALLER_USER_HANDLE));
1145
Makoto Onukic8a5a552015-11-19 14:29:12 -08001146 assertEquals(admin2, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001147
1148 // Then check getDeviceOwnerAdminLocked().
1149 assertEquals(admin2, dpms.getDeviceOwnerAdminLocked().info.getComponent());
1150 assertEquals(DpmMockContext.CALLER_UID, dpms.getDeviceOwnerAdminLocked().getUid());
1151 }
1152
1153 /**
1154 * This essentially tests
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08001155 * {@code DevicePolicyManagerService.findOwnerComponentIfNecessaryLocked()}. (which is
1156 * private.)
Makoto Onukia52562c2015-10-01 16:12:31 -07001157 *
1158 * We didn't use to persist the DO component class name, but now we do, and the above method
1159 * finds the right component from a package name upon migration.
1160 */
1161 public void testDeviceOwnerMigration() throws Exception {
Victor Change29cd472016-03-02 20:57:42 +00001162 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Makoto Onukia52562c2015-10-01 16:12:31 -07001163 checkDeviceOwnerWithMultipleDeviceAdmins();
1164
1165 // Overwrite the device owner setting and clears the clas name.
1166 dpms.mOwners.setDeviceOwner(
1167 new ComponentName(admin2.getPackageName(), ""),
1168 "owner-name", DpmMockContext.CALLER_USER_HANDLE);
1169 dpms.mOwners.writeDeviceOwner();
1170
1171 // Make sure the DO component name doesn't have a class name.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001172 assertEquals("", dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false).getClassName());
Makoto Onukia52562c2015-10-01 16:12:31 -07001173
1174 // Then create a new DPMS to have it load the settings from files.
Makoto Onuki068c54a2015-10-13 14:34:03 -07001175 when(mContext.userManager.getUserRestrictions(any(UserHandle.class)))
1176 .thenReturn(new Bundle());
Makoto Onukia52562c2015-10-01 16:12:31 -07001177 initializeDpms();
1178
1179 // Now the DO component name is a full name.
1180 // *BUT* because both admin1 and admin2 belong to the same package, we think admin1 is the
1181 // DO.
Makoto Onukic8a5a552015-11-19 14:29:12 -08001182 assertEquals(admin1, dpms.getDeviceOwnerComponent(/* callingUserOnly =*/ false));
Makoto Onukia52562c2015-10-01 16:12:31 -07001183 }
1184
Makoto Onukib643fb02015-09-22 15:03:44 -07001185 public void testSetGetApplicationRestriction() {
1186 setAsProfileOwner(admin1);
Edman Anjosf9946772016-11-28 16:35:15 +01001187 mContext.packageName = admin1.getPackageName();
Makoto Onukib643fb02015-09-22 15:03:44 -07001188
1189 {
1190 Bundle rest = new Bundle();
1191 rest.putString("KEY_STRING", "Foo1");
1192 dpm.setApplicationRestrictions(admin1, "pkg1", rest);
1193 }
1194
1195 {
1196 Bundle rest = new Bundle();
1197 rest.putString("KEY_STRING", "Foo2");
1198 dpm.setApplicationRestrictions(admin1, "pkg2", rest);
1199 }
1200
1201 {
1202 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg1");
1203 assertNotNull(returned);
1204 assertEquals(returned.size(), 1);
1205 assertEquals(returned.get("KEY_STRING"), "Foo1");
1206 }
1207
1208 {
1209 Bundle returned = dpm.getApplicationRestrictions(admin1, "pkg2");
1210 assertNotNull(returned);
1211 assertEquals(returned.size(), 1);
1212 assertEquals(returned.get("KEY_STRING"), "Foo2");
1213 }
1214
1215 dpm.setApplicationRestrictions(admin1, "pkg2", new Bundle());
1216 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg2").size());
1217 }
Makoto Onukia4f11972015-10-01 13:19:58 -07001218
Edman Anjosf9946772016-11-28 16:35:15 +01001219 /**
1220 * Setup a package in the package manager mock. Useful for faking installed applications.
1221 *
1222 * @param packageName the name of the package to be setup
1223 * @param appId the application ID to be given to the package
1224 * @return the UID of the package as known by the mock package manager
1225 */
1226 private int setupPackageInPackageManager(final String packageName, final int appId)
1227 throws Exception {
1228 // Make the PackageManager return the package instead of throwing a NameNotFoundException
1229 final PackageInfo pi = new PackageInfo();
1230 pi.applicationInfo = new ApplicationInfo();
1231 pi.applicationInfo.flags = ApplicationInfo.FLAG_HAS_CODE;
1232 doReturn(pi).when(mContext.ipackageManager).getPackageInfo(
1233 eq(packageName),
1234 anyInt(),
1235 eq(DpmMockContext.CALLER_USER_HANDLE));
1236 // Setup application UID with the PackageManager
1237 final int uid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE, appId);
1238 doReturn(uid).when(mContext.packageManager).getPackageUidAsUser(
1239 eq(packageName),
1240 eq(DpmMockContext.CALLER_USER_HANDLE));
1241 // Associate packageName to uid
1242 doReturn(packageName).when(mContext.ipackageManager).getNameForUid(eq(uid));
1243 doReturn(new String[]{packageName})
1244 .when(mContext.ipackageManager).getPackagesForUid(eq(uid));
1245 return uid;
1246 }
1247
Robin Lee7f5c91c2017-02-08 21:27:02 +00001248 public void testCertificateDisclosure() throws Exception {
1249 final int userId = DpmMockContext.CALLER_USER_HANDLE;
1250 final UserHandle user = UserHandle.of(userId);
1251
1252 mContext.applicationInfo = new ApplicationInfo();
1253 mContext.callerPermissions.add(permission.MANAGE_USERS);
1254 mContext.packageName = "com.android.frameworks.servicestests";
Robin Lee2c68dad2017-03-17 12:50:24 +00001255 mContext.addPackageContext(user, mContext);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001256 when(mContext.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
1257
Robin Leeabaa0692017-02-20 20:54:22 +00001258 StringParceledListSlice oneCert = asSlice(new String[] {"1"});
1259 StringParceledListSlice fourCerts = asSlice(new String[] {"1", "2", "3", "4"});
Robin Lee7f5c91c2017-02-08 21:27:02 +00001260
1261 final String TEST_STRING = "Test for exactly 2 certs out of 4";
1262 doReturn(TEST_STRING).when(mContext.resources).getQuantityText(anyInt(), eq(2));
1263
1264 // Given that we have exactly one certificate installed,
1265 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(oneCert);
1266 // when that certificate is approved,
Robin Leeabaa0692017-02-20 20:54:22 +00001267 dpms.approveCaCert(oneCert.getList().get(0), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001268 // a notification should not be shown.
1269 verify(mContext.notificationManager, timeout(1000))
1270 .cancelAsUser(anyString(), anyInt(), eq(user));
1271
1272 // Given that we have four certificates installed,
1273 when(mContext.keyChainConnection.getService().getUserCaAliases()).thenReturn(fourCerts);
1274 // when two of them are approved (one of them approved twice hence no action),
Robin Leeabaa0692017-02-20 20:54:22 +00001275 dpms.approveCaCert(fourCerts.getList().get(0), userId, true);
1276 dpms.approveCaCert(fourCerts.getList().get(1), userId, true);
Robin Lee7f5c91c2017-02-08 21:27:02 +00001277 // a notification should be shown saying that there are two certificates left to approve.
1278 verify(mContext.notificationManager, timeout(1000))
1279 .notifyAsUser(anyString(), anyInt(), argThat(
1280 new BaseMatcher<Notification>() {
1281 @Override
1282 public boolean matches(Object item) {
1283 final Notification noti = (Notification) item;
1284 return TEST_STRING.equals(
1285 noti.extras.getString(Notification.EXTRA_TITLE));
1286 }
1287 @Override
1288 public void describeTo(Description description) {
1289 description.appendText(
1290 "Notification{title=\"" + TEST_STRING + "\"}");
1291 }
1292 }), eq(user));
1293 }
1294
Edman Anjosf9946772016-11-28 16:35:15 +01001295 /**
1296 * Simple test for delegate set/get and general delegation. Tests verifying that delegated
1297 * privileges can acually be exercised by a delegate are not covered here.
1298 */
1299 public void testDelegation() throws Exception {
1300 setAsProfileOwner(admin1);
1301
1302 final int userHandle = DpmMockContext.CALLER_USER_HANDLE;
1303
1304 // Given two packages
1305 final String CERT_DELEGATE = "com.delegate.certs";
1306 final String RESTRICTIONS_DELEGATE = "com.delegate.apprestrictions";
1307 final int CERT_DELEGATE_UID = setupPackageInPackageManager(CERT_DELEGATE, 20988);
1308 final int RESTRICTIONS_DELEGATE_UID = setupPackageInPackageManager(RESTRICTIONS_DELEGATE,
1309 20989);
1310
1311 // On delegation
1312 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1313 mContext.packageName = admin1.getPackageName();
1314 dpm.setCertInstallerPackage(admin1, CERT_DELEGATE);
1315 dpm.setApplicationRestrictionsManagingPackage(admin1, RESTRICTIONS_DELEGATE);
1316
1317 // DPMS correctly stores and retrieves the delegates
1318 DevicePolicyManagerService.DevicePolicyData policy = dpms.mUserData.get(userHandle);
1319 assertEquals(2, policy.mDelegationMap.size());
1320 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(CERT_DELEGATE),
1321 DELEGATION_CERT_INSTALL);
1322 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, CERT_DELEGATE),
1323 DELEGATION_CERT_INSTALL);
1324 assertEquals(CERT_DELEGATE, dpm.getCertInstallerPackage(admin1));
1325 MoreAsserts.assertContentsInAnyOrder(policy.mDelegationMap.get(RESTRICTIONS_DELEGATE),
1326 DELEGATION_APP_RESTRICTIONS);
1327 MoreAsserts.assertContentsInAnyOrder(dpm.getDelegatedScopes(admin1, RESTRICTIONS_DELEGATE),
1328 DELEGATION_APP_RESTRICTIONS);
1329 assertEquals(RESTRICTIONS_DELEGATE, dpm.getApplicationRestrictionsManagingPackage(admin1));
1330
1331 // On calling install certificate APIs from an unauthorized process
1332 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1333 mContext.packageName = RESTRICTIONS_DELEGATE;
1334
1335 // DPMS throws a SecurityException
1336 try {
1337 dpm.installCaCert(null, null);
1338 fail("Didn't throw SecurityException on unauthorized access");
1339 } catch (SecurityException expected) {
1340 }
1341
1342 // On calling install certificate APIs from an authorized process
1343 mContext.binder.callingUid = CERT_DELEGATE_UID;
1344 mContext.packageName = CERT_DELEGATE;
1345
1346 // DPMS executes without a SecurityException
1347 try {
1348 dpm.installCaCert(null, null);
1349 } catch (SecurityException unexpected) {
1350 fail("Threw SecurityException on authorized access");
1351 } catch (NullPointerException expected) {
1352 }
1353
1354 // On removing a delegate
1355 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1356 mContext.packageName = admin1.getPackageName();
1357 dpm.setCertInstallerPackage(admin1, null);
1358
1359 // DPMS does not allow access to ex-delegate
1360 mContext.binder.callingUid = CERT_DELEGATE_UID;
1361 mContext.packageName = CERT_DELEGATE;
1362 try {
1363 dpm.installCaCert(null, null);
1364 fail("Didn't throw SecurityException on unauthorized access");
1365 } catch (SecurityException expected) {
1366 }
1367
1368 // But still allows access to other existing delegates
1369 mContext.binder.callingUid = RESTRICTIONS_DELEGATE_UID;
1370 mContext.packageName = RESTRICTIONS_DELEGATE;
1371 try {
1372 dpm.getApplicationRestrictions(null, "pkg");
1373 } catch (SecurityException expected) {
1374 fail("Threw SecurityException on authorized access");
1375 }
1376 }
1377
Esteban Talaverabf60f722015-12-10 16:26:44 +00001378 public void testApplicationRestrictionsManagingApp() throws Exception {
1379 setAsProfileOwner(admin1);
1380
Rubin Xued1928a2016-02-11 17:23:06 +00001381 final String nonExistAppRestrictionsManagerPackage = "com.google.app.restrictions.manager2";
Esteban Talaverabf60f722015-12-10 16:26:44 +00001382 final String appRestrictionsManagerPackage = "com.google.app.restrictions.manager";
1383 final int appRestrictionsManagerAppId = 20987;
Edman Anjosf9946772016-11-28 16:35:15 +01001384 final int appRestrictionsManagerUid = setupPackageInPackageManager(
1385 appRestrictionsManagerPackage, appRestrictionsManagerAppId);
Rubin Xued1928a2016-02-11 17:23:06 +00001386
Esteban Talaverabf60f722015-12-10 16:26:44 +00001387 // appRestrictionsManager package shouldn't be able to manage restrictions as the PO hasn't
1388 // delegated that permission yet.
Edman Anjosf9946772016-11-28 16:35:15 +01001389 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
1390 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001391 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1392 Bundle rest = new Bundle();
1393 rest.putString("KEY_STRING", "Foo1");
1394 try {
1395 dpm.setApplicationRestrictions(null, "pkg1", rest);
1396 fail("Didn't throw expected SecurityException");
1397 } catch (SecurityException expected) {
1398 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001399 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1400 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001401 }
1402 try {
1403 dpm.getApplicationRestrictions(null, "pkg1");
1404 fail("Didn't throw expected SecurityException");
1405 } catch (SecurityException expected) {
1406 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001407 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1408 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001409 }
1410
1411 // Check via the profile owner that no restrictions were set.
1412 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001413 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001414 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1415
Rubin Xued1928a2016-02-11 17:23:06 +00001416 // Check the API does not allow setting a non-existent package
1417 try {
1418 dpm.setApplicationRestrictionsManagingPackage(admin1,
1419 nonExistAppRestrictionsManagerPackage);
1420 fail("Non-existent app set as app restriction manager.");
Victor Changcd14c0a2016-03-16 19:10:15 +00001421 } catch (PackageManager.NameNotFoundException expected) {
Rubin Xued1928a2016-02-11 17:23:06 +00001422 MoreAsserts.assertContainsRegex(
Victor Changcd14c0a2016-03-16 19:10:15 +00001423 nonExistAppRestrictionsManagerPackage, expected.getMessage());
Rubin Xued1928a2016-02-11 17:23:06 +00001424 }
1425
Esteban Talaverabf60f722015-12-10 16:26:44 +00001426 // Let appRestrictionsManagerPackage manage app restrictions
1427 dpm.setApplicationRestrictionsManagingPackage(admin1, appRestrictionsManagerPackage);
1428 assertEquals(appRestrictionsManagerPackage,
1429 dpm.getApplicationRestrictionsManagingPackage(admin1));
1430
1431 // Now that package should be able to set and retrieve app restrictions.
1432 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001433 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001434 assertTrue(dpm.isCallerApplicationRestrictionsManagingPackage());
1435 dpm.setApplicationRestrictions(null, "pkg1", rest);
1436 Bundle returned = dpm.getApplicationRestrictions(null, "pkg1");
1437 assertEquals(1, returned.size(), 1);
1438 assertEquals("Foo1", returned.get("KEY_STRING"));
1439
1440 // The same app running on a separate user shouldn't be able to manage app restrictions.
1441 mContext.binder.callingUid = UserHandle.getUid(
1442 UserHandle.USER_SYSTEM, appRestrictionsManagerAppId);
1443 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1444 try {
1445 dpm.setApplicationRestrictions(null, "pkg1", rest);
1446 fail("Didn't throw expected SecurityException");
1447 } catch (SecurityException expected) {
1448 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001449 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1450 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001451 }
1452
1453 // The DPM is still able to manage app restrictions, even if it allowed another app to do it
1454 // too.
1455 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Edman Anjosf9946772016-11-28 16:35:15 +01001456 mContext.packageName = admin1.getPackageName();
Esteban Talaverabf60f722015-12-10 16:26:44 +00001457 assertEquals(returned, dpm.getApplicationRestrictions(admin1, "pkg1"));
1458 dpm.setApplicationRestrictions(admin1, "pkg1", null);
1459 assertEquals(0, dpm.getApplicationRestrictions(admin1, "pkg1").size());
1460
1461 // Removing the ability for the package to manage app restrictions.
1462 dpm.setApplicationRestrictionsManagingPackage(admin1, null);
1463 assertNull(dpm.getApplicationRestrictionsManagingPackage(admin1));
1464 mContext.binder.callingUid = appRestrictionsManagerUid;
Edman Anjosf9946772016-11-28 16:35:15 +01001465 mContext.packageName = appRestrictionsManagerPackage;
Esteban Talaverabf60f722015-12-10 16:26:44 +00001466 assertFalse(dpm.isCallerApplicationRestrictionsManagingPackage());
1467 try {
1468 dpm.setApplicationRestrictions(null, "pkg1", null);
1469 fail("Didn't throw expected SecurityException");
1470 } catch (SecurityException expected) {
1471 MoreAsserts.assertContainsRegex(
Edman Anjosf9946772016-11-28 16:35:15 +01001472 "Caller with uid \\d+ is not a delegate of scope delegation-app-restrictions.",
1473 expected.getMessage());
Esteban Talaverabf60f722015-12-10 16:26:44 +00001474 }
1475 }
1476
Makoto Onukia4f11972015-10-01 13:19:58 -07001477 public void testSetUserRestriction_asDo() throws Exception {
1478 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
Makoto Onukic8a5a552015-11-19 14:29:12 -08001479 mContext.callerPermissions.add(permission.MANAGE_USERS);
Makoto Onukia4f11972015-10-01 13:19:58 -07001480 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1481 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1482
1483 // First, set DO.
1484
1485 // Call from a process on the system user.
1486 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1487
1488 // Make sure admin1 is installed on system user.
1489 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
Makoto Onukia4f11972015-10-01 13:19:58 -07001490
1491 // Call.
1492 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
Makoto Onukia52562c2015-10-01 16:12:31 -07001493 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
Makoto Onukia4f11972015-10-01 13:19:58 -07001494 UserHandle.USER_SYSTEM));
1495
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001496 // Check that the user restrictions that are enabled by default are set. Then unset them.
1497 String[] defaultRestrictions = UserRestrictionsUtils
Esteban Talavera548a04b2016-12-20 15:22:30 +00001498 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001499 DpmTestUtils.assertRestrictions(
1500 DpmTestUtils.newRestrictions(defaultRestrictions),
1501 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1502 );
1503 DpmTestUtils.assertRestrictions(
1504 DpmTestUtils.newRestrictions(defaultRestrictions),
1505 dpm.getUserRestrictions(admin1)
1506 );
Esteban Talavera548a04b2016-12-20 15:22:30 +00001507 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1508 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001509 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001510 eq(true) /* isDeviceOwner */,
1511 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001512 );
1513 reset(mContext.userManagerInternal);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00001514
1515 for (String restriction : defaultRestrictions) {
1516 dpm.clearUserRestriction(admin1, restriction);
1517 }
1518
Esteban Talavera548a04b2016-12-20 15:22:30 +00001519 assertNoDeviceOwnerRestrictions();
Pavel Grafov6a40f092016-10-25 15:46:51 +01001520 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001521
1522 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1523 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1524 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001525 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1526 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001527 reset(mContext.userManagerInternal);
1528
Makoto Onukia4f11972015-10-01 13:19:58 -07001529 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001530 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1531 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001532 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS,
1533 UserManager.DISALLOW_ADD_USER),
1534 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001535 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001536
Makoto Onuki068c54a2015-10-13 14:34:03 -07001537 DpmTestUtils.assertRestrictions(
1538 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001539 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki068c54a2015-10-13 14:34:03 -07001540 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1541 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001542 DpmTestUtils.assertRestrictions(
1543 DpmTestUtils.newRestrictions(
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001544 UserManager.DISALLOW_ADD_USER, UserManager.DISALLOW_OUTGOING_CALLS),
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001545 dpm.getUserRestrictions(admin1)
1546 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001547
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001548 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1549 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1550 eq(UserHandle.USER_SYSTEM),
1551 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001552 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001553 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001554
Makoto Onuki068c54a2015-10-13 14:34:03 -07001555 DpmTestUtils.assertRestrictions(
1556 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1557 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1558 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001559 DpmTestUtils.assertRestrictions(
1560 DpmTestUtils.newRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
1561 dpm.getUserRestrictions(admin1)
1562 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001563
1564 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001565 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1566 eq(UserHandle.USER_SYSTEM),
1567 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001568 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001569 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001570
Esteban Talavera548a04b2016-12-20 15:22:30 +00001571 assertNoDeviceOwnerRestrictions();
Makoto Onukia4f11972015-10-01 13:19:58 -07001572
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001573 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE are PO restrictions, but when
1574 // DO sets them, the scope is global.
1575 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1576 reset(mContext.userManagerInternal);
1577 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1578 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1579 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001580 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001581 UserManager.DISALLOW_UNMUTE_MICROPHONE),
1582 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001583 reset(mContext.userManagerInternal);
1584
1585 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1586 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
Pavel Grafov6a40f092016-10-25 15:46:51 +01001587 reset(mContext.userManagerInternal);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001588
1589 // More tests.
1590 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADD_USER);
1591 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1592 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001593 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADD_USER),
1594 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001595 reset(mContext.userManagerInternal);
1596
1597 dpm.addUserRestriction(admin1, UserManager.DISALLOW_FUN);
1598 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1599 eq(UserHandle.USER_SYSTEM),
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001600 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001601 UserManager.DISALLOW_ADD_USER),
1602 eq(true), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001603 reset(mContext.userManagerInternal);
1604
1605 dpm.setCameraDisabled(admin1, true);
1606 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1607 eq(UserHandle.USER_SYSTEM),
1608 // DISALLOW_CAMERA will be applied to both local and global.
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001609 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001610 UserManager.DISALLOW_ADD_USER),
1611 eq(true), eq(CAMERA_DISABLED_GLOBALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001612 reset(mContext.userManagerInternal);
1613
1614 // Set up another DA and let it disable camera. Now DISALLOW_CAMERA will only be applied
1615 // locally.
1616 dpm.setCameraDisabled(admin1, false);
1617 reset(mContext.userManagerInternal);
1618
1619 setUpPackageManagerForAdmin(admin2, DpmMockContext.CALLER_SYSTEM_USER_UID);
1620 dpm.setActiveAdmin(admin2, /* replace =*/ false, UserHandle.USER_SYSTEM);
1621 dpm.setCameraDisabled(admin2, true);
1622
1623 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1624 eq(UserHandle.USER_SYSTEM),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001625 // DISALLOW_CAMERA will be applied to both local and global. <- TODO: fix this
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001626 MockUtils.checkUserRestrictions(UserManager.DISALLOW_FUN,
Pavel Grafov6a40f092016-10-25 15:46:51 +01001627 UserManager.DISALLOW_ADD_USER),
1628 eq(true), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001629 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001630 // TODO Make sure restrictions are written to the file.
1631 }
1632
1633 public void testSetUserRestriction_asPo() {
1634 setAsProfileOwner(admin1);
1635
Makoto Onuki068c54a2015-10-13 14:34:03 -07001636 DpmTestUtils.assertRestrictions(
1637 DpmTestUtils.newRestrictions(),
1638 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1639 .ensureUserRestrictions()
1640 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001641
1642 dpm.addUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001643 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1644 eq(DpmMockContext.CALLER_USER_HANDLE),
1645 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001646 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001647 reset(mContext.userManagerInternal);
1648
Makoto Onukia4f11972015-10-01 13:19:58 -07001649 dpm.addUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001650 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1651 eq(DpmMockContext.CALLER_USER_HANDLE),
1652 MockUtils.checkUserRestrictions(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1653 UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001654 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001655 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001656
Makoto Onuki068c54a2015-10-13 14:34:03 -07001657 DpmTestUtils.assertRestrictions(
1658 DpmTestUtils.newRestrictions(
1659 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1660 UserManager.DISALLOW_OUTGOING_CALLS
1661 ),
1662 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1663 .ensureUserRestrictions()
1664 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001665 DpmTestUtils.assertRestrictions(
1666 DpmTestUtils.newRestrictions(
1667 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES,
1668 UserManager.DISALLOW_OUTGOING_CALLS
1669 ),
1670 dpm.getUserRestrictions(admin1)
1671 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001672
1673 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001674 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1675 eq(DpmMockContext.CALLER_USER_HANDLE),
1676 MockUtils.checkUserRestrictions(UserManager.DISALLOW_OUTGOING_CALLS),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001677 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001678 reset(mContext.userManagerInternal);
Makoto Onuki068c54a2015-10-13 14:34:03 -07001679
1680 DpmTestUtils.assertRestrictions(
1681 DpmTestUtils.newRestrictions(
1682 UserManager.DISALLOW_OUTGOING_CALLS
1683 ),
1684 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1685 .ensureUserRestrictions()
1686 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001687 DpmTestUtils.assertRestrictions(
1688 DpmTestUtils.newRestrictions(
1689 UserManager.DISALLOW_OUTGOING_CALLS
1690 ),
1691 dpm.getUserRestrictions(admin1)
1692 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001693
1694 dpm.clearUserRestriction(admin1, UserManager.DISALLOW_OUTGOING_CALLS);
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001695 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1696 eq(DpmMockContext.CALLER_USER_HANDLE),
1697 MockUtils.checkUserRestrictions(),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001698 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001699 reset(mContext.userManagerInternal);
Makoto Onukia4f11972015-10-01 13:19:58 -07001700
Makoto Onuki068c54a2015-10-13 14:34:03 -07001701 DpmTestUtils.assertRestrictions(
1702 DpmTestUtils.newRestrictions(),
1703 dpms.getProfileOwnerAdminLocked(DpmMockContext.CALLER_USER_HANDLE)
1704 .ensureUserRestrictions()
1705 );
Makoto Onuki3a3092f2015-10-30 11:07:51 -07001706 DpmTestUtils.assertRestrictions(
1707 DpmTestUtils.newRestrictions(),
1708 dpm.getUserRestrictions(admin1)
1709 );
Makoto Onukia4f11972015-10-01 13:19:58 -07001710
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001711 // DISALLOW_ADJUST_VOLUME and DISALLOW_UNMUTE_MICROPHONE can be set by PO too, even
1712 // though when DO sets them they'll be applied globally.
1713 dpm.addUserRestriction(admin1, UserManager.DISALLOW_ADJUST_VOLUME);
1714 reset(mContext.userManagerInternal);
1715 dpm.addUserRestriction(admin1, UserManager.DISALLOW_UNMUTE_MICROPHONE);
1716 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1717 eq(DpmMockContext.CALLER_USER_HANDLE),
1718 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
1719 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001720 eq(false), eq(CAMERA_NOT_DISABLED));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001721 reset(mContext.userManagerInternal);
1722
1723 dpm.setCameraDisabled(admin1, true);
1724 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1725 eq(DpmMockContext.CALLER_USER_HANDLE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001726 MockUtils.checkUserRestrictions(UserManager.DISALLOW_ADJUST_VOLUME,
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001727 UserManager.DISALLOW_UNMUTE_MICROPHONE),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001728 eq(false), eq(CAMERA_DISABLED_LOCALLY));
Makoto Onuki1a2cd742015-11-16 13:51:27 -08001729 reset(mContext.userManagerInternal);
1730
Makoto Onukia4f11972015-10-01 13:19:58 -07001731 // TODO Make sure restrictions are written to the file.
1732 }
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001733
Esteban Talavera548a04b2016-12-20 15:22:30 +00001734
1735 public void testDefaultEnabledUserRestrictions() throws Exception {
1736 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1737 mContext.callerPermissions.add(permission.MANAGE_USERS);
1738 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1739 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1740
1741 // First, set DO.
1742
1743 // Call from a process on the system user.
1744 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1745
1746 // Make sure admin1 is installed on system user.
1747 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1748
1749 dpm.setActiveAdmin(admin1, /* replace =*/ false, UserHandle.USER_SYSTEM);
1750 assertTrue(dpm.setDeviceOwner(admin1, "owner-name",
1751 UserHandle.USER_SYSTEM));
1752
1753 // Check that the user restrictions that are enabled by default are set. Then unset them.
1754 String[] defaultRestrictions = UserRestrictionsUtils
1755 .getDefaultEnabledForDeviceOwner().toArray(new String[0]);
1756 assertTrue(defaultRestrictions.length > 0);
1757 DpmTestUtils.assertRestrictions(
1758 DpmTestUtils.newRestrictions(defaultRestrictions),
1759 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1760 );
1761 DpmTestUtils.assertRestrictions(
1762 DpmTestUtils.newRestrictions(defaultRestrictions),
1763 dpm.getUserRestrictions(admin1)
1764 );
1765 verify(mContext.userManagerInternal).setDevicePolicyUserRestrictions(
1766 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001767 MockUtils.checkUserRestrictions(defaultRestrictions),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001768 eq(true) /* isDeviceOwner */,
1769 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001770 );
1771 reset(mContext.userManagerInternal);
1772
1773 for (String restriction : defaultRestrictions) {
1774 dpm.clearUserRestriction(admin1, restriction);
1775 }
1776
1777 assertNoDeviceOwnerRestrictions();
1778
1779 // Initialize DPMS again and check that the user restriction wasn't enabled again.
1780 reset(mContext.userManagerInternal);
1781 initializeDpms();
1782 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1783 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1784
1785 assertNoDeviceOwnerRestrictions();
1786
1787 // Add a new restriction to the default set, initialize DPMS, and check that the restriction
1788 // is set as it wasn't enabled during setDeviceOwner.
1789 final String newDefaultEnabledRestriction = UserManager.DISALLOW_REMOVE_MANAGED_PROFILE;
1790 assertFalse(UserRestrictionsUtils
1791 .getDefaultEnabledForDeviceOwner().contains(newDefaultEnabledRestriction));
1792 UserRestrictionsUtils
1793 .getDefaultEnabledForDeviceOwner().add(newDefaultEnabledRestriction);
1794 try {
1795 reset(mContext.userManagerInternal);
1796 initializeDpms();
1797 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1798 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1799
1800 DpmTestUtils.assertRestrictions(
1801 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1802 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1803 );
1804 DpmTestUtils.assertRestrictions(
1805 DpmTestUtils.newRestrictions(newDefaultEnabledRestriction),
1806 dpm.getUserRestrictions(admin1)
1807 );
1808 verify(mContext.userManagerInternal, atLeast(1)).setDevicePolicyUserRestrictions(
1809 eq(UserHandle.USER_SYSTEM),
Nicolas Prevot2ea46fe2017-01-05 10:29:34 +00001810 MockUtils.checkUserRestrictions(newDefaultEnabledRestriction),
Pavel Grafov6a40f092016-10-25 15:46:51 +01001811 eq(true) /* isDeviceOwner */,
1812 eq(CAMERA_NOT_DISABLED)
Esteban Talavera548a04b2016-12-20 15:22:30 +00001813 );
1814 reset(mContext.userManagerInternal);
1815
1816 // Remove the restriction.
1817 dpm.clearUserRestriction(admin1, newDefaultEnabledRestriction);
1818
1819 // Initialize DPMS again. The restriction shouldn't be enabled for a second time.
1820 initializeDpms();
1821 assertTrue(dpm.isDeviceOwnerApp(admin1.getPackageName()));
1822 assertNotNull(dpms.getDeviceOwnerAdminLocked());
1823 assertNoDeviceOwnerRestrictions();
1824 } finally {
1825 UserRestrictionsUtils
1826 .getDefaultEnabledForDeviceOwner().remove(newDefaultEnabledRestriction);
1827 }
1828 }
1829
1830 private void assertNoDeviceOwnerRestrictions() {
1831 DpmTestUtils.assertRestrictions(
1832 DpmTestUtils.newRestrictions(),
1833 dpms.getDeviceOwnerAdminLocked().ensureUserRestrictions()
1834 );
1835 DpmTestUtils.assertRestrictions(
1836 DpmTestUtils.newRestrictions(),
1837 dpm.getUserRestrictions(admin1)
1838 );
1839 }
1840
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001841 public void testGetMacAddress() throws Exception {
1842 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1843 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1844 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
1845
1846 // In this test, change the caller user to "system".
1847 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1848
1849 // Make sure admin1 is installed on system user.
1850 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1851
1852 // Test 1. Caller doesn't have DO or DA.
1853 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001854 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001855 fail();
1856 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001857 MoreAsserts.assertContainsRegex("No active admin", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001858 }
1859
1860 // DO needs to be an DA.
1861 dpm.setActiveAdmin(admin1, /* replace =*/ false);
1862 assertTrue(dpm.isAdminActive(admin1));
1863
1864 // Test 2. Caller has DA, but not DO.
1865 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001866 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001867 fail();
1868 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001869 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001870 }
1871
1872 // Test 3. Caller has PO, but not DO.
1873 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1874 try {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001875 dpm.getWifiMacAddress(admin1);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001876 fail();
1877 } catch (SecurityException e) {
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001878 MoreAsserts.assertContainsRegex("does not own the device", e.getMessage());
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001879 }
1880
1881 // Remove PO.
1882 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001883 dpm.setActiveAdmin(admin1, false);
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001884 // Test 4, Caller is DO now.
1885 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1886
1887 // 4-1. But no WifiInfo.
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001888 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001889
1890 // 4-2. Returns WifiInfo, but with the default MAC.
1891 when(mContext.wifiManager.getConnectionInfo()).thenReturn(new WifiInfo());
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001892 assertNull(dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001893
1894 // 4-3. With a real MAC address.
1895 final WifiInfo wi = new WifiInfo();
1896 wi.setMacAddress("11:22:33:44:55:66");
1897 when(mContext.wifiManager.getConnectionInfo()).thenReturn(wi);
Sudheer Shanka3cb4da12016-03-07 18:51:49 -08001898 assertEquals("11:22:33:44:55:66", dpm.getWifiMacAddress(admin1));
Makoto Onukia31ebbc2015-11-23 17:15:21 -08001899 }
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001900
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001901 public void testReboot() throws Exception {
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001902 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1903 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
1904
1905 // In this test, change the caller user to "system".
1906 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
1907
1908 // Make sure admin1 is installed on system user.
1909 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
1910
1911 // Set admin1 as DA.
1912 dpm.setActiveAdmin(admin1, false);
1913 assertTrue(dpm.isAdminActive(admin1));
1914 try {
1915 dpm.reboot(admin1);
1916 fail("DA calls DPM.reboot(), did not throw expected SecurityException");
1917 } catch (SecurityException expected) {
1918 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1919 }
1920
1921 // Set admin1 as PO.
1922 assertTrue(dpm.setProfileOwner(admin1, null, UserHandle.USER_SYSTEM));
1923 try {
1924 dpm.reboot(admin1);
1925 fail("PO calls DPM.reboot(), did not throw expected SecurityException");
1926 } catch (SecurityException expected) {
1927 MoreAsserts.assertContainsRegex("does not own the device", expected.getMessage());
1928 }
1929
1930 // Remove PO and add DO.
1931 dpm.clearProfileOwner(admin1);
Suprabh Shukla3cb2b492016-08-09 17:20:57 -07001932 dpm.setActiveAdmin(admin1, false);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001933 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
1934
Mahaver Chopra1216ae52016-03-11 15:39:48 +00001935 // admin1 is DO.
1936 // Set current call state of device to ringing.
1937 when(mContext.telephonyManager.getCallState())
1938 .thenReturn(TelephonyManager.CALL_STATE_RINGING);
1939 try {
1940 dpm.reboot(admin1);
1941 fail("DPM.reboot() called when receiveing a call, should thrown IllegalStateException");
1942 } catch (IllegalStateException expected) {
1943 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1944 }
1945
1946 // Set current call state of device to dialing/active.
1947 when(mContext.telephonyManager.getCallState())
1948 .thenReturn(TelephonyManager.CALL_STATE_OFFHOOK);
1949 try {
1950 dpm.reboot(admin1);
1951 fail("DPM.reboot() called when dialing, should thrown IllegalStateException");
1952 } catch (IllegalStateException expected) {
1953 MoreAsserts.assertContainsRegex("ongoing call on the device", expected.getMessage());
1954 }
1955
1956 // Set current call state of device to idle.
1957 when(mContext.telephonyManager.getCallState()).thenReturn(TelephonyManager.CALL_STATE_IDLE);
Mahaver Chopraf8373b52015-12-23 14:42:18 +00001958 dpm.reboot(admin1);
1959 }
Kenny Guy06de4e72015-12-22 12:07:39 +00001960
1961 public void testSetGetSupportText() {
1962 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
1963 dpm.setActiveAdmin(admin1, true);
1964 dpm.setActiveAdmin(admin2, true);
1965 mContext.callerPermissions.remove(permission.MANAGE_DEVICE_ADMINS);
1966
1967 // Null default support messages.
1968 {
1969 assertNull(dpm.getLongSupportMessage(admin1));
1970 assertNull(dpm.getShortSupportMessage(admin1));
1971 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
1972 assertNull(dpm.getShortSupportMessageForUser(admin1,
1973 DpmMockContext.CALLER_USER_HANDLE));
1974 assertNull(dpm.getLongSupportMessageForUser(admin1,
1975 DpmMockContext.CALLER_USER_HANDLE));
1976 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
1977 }
1978
1979 // Only system can call the per user versions.
1980 {
1981 try {
1982 dpm.getShortSupportMessageForUser(admin1,
1983 DpmMockContext.CALLER_USER_HANDLE);
1984 fail("Only system should be able to call getXXXForUser versions");
1985 } catch (SecurityException expected) {
1986 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1987 }
1988 try {
1989 dpm.getLongSupportMessageForUser(admin1,
1990 DpmMockContext.CALLER_USER_HANDLE);
1991 fail("Only system should be able to call getXXXForUser versions");
1992 } catch (SecurityException expected) {
1993 MoreAsserts.assertContainsRegex("message for user", expected.getMessage());
1994 }
1995 }
1996
1997 // Can't set message for admin in another uid.
1998 {
1999 mContext.binder.callingUid = DpmMockContext.CALLER_UID + 1;
2000 try {
2001 dpm.setShortSupportMessage(admin1, "Some text");
2002 fail("Admins should only be able to change their own support text.");
2003 } catch (SecurityException expected) {
2004 MoreAsserts.assertContainsRegex("is not owned by uid", expected.getMessage());
2005 }
2006 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2007 }
2008
2009 // Set/Get short returns what it sets and other admins text isn't changed.
2010 {
2011 final String supportText = "Some text to test with.";
2012 dpm.setShortSupportMessage(admin1, supportText);
2013 assertEquals(supportText, dpm.getShortSupportMessage(admin1));
2014 assertNull(dpm.getLongSupportMessage(admin1));
2015 assertNull(dpm.getShortSupportMessage(admin2));
2016
2017 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2018 assertEquals(supportText, dpm.getShortSupportMessageForUser(admin1,
2019 DpmMockContext.CALLER_USER_HANDLE));
2020 assertNull(dpm.getShortSupportMessageForUser(admin2,
2021 DpmMockContext.CALLER_USER_HANDLE));
2022 assertNull(dpm.getLongSupportMessageForUser(admin1,
2023 DpmMockContext.CALLER_USER_HANDLE));
2024 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2025
2026 dpm.setShortSupportMessage(admin1, null);
2027 assertNull(dpm.getShortSupportMessage(admin1));
2028 }
2029
2030 // Set/Get long returns what it sets and other admins text isn't changed.
2031 {
2032 final String supportText = "Some text to test with.\nWith more text.";
2033 dpm.setLongSupportMessage(admin1, supportText);
2034 assertEquals(supportText, dpm.getLongSupportMessage(admin1));
2035 assertNull(dpm.getShortSupportMessage(admin1));
2036 assertNull(dpm.getLongSupportMessage(admin2));
2037
2038 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
2039 assertEquals(supportText, dpm.getLongSupportMessageForUser(admin1,
2040 DpmMockContext.CALLER_USER_HANDLE));
2041 assertNull(dpm.getLongSupportMessageForUser(admin2,
2042 DpmMockContext.CALLER_USER_HANDLE));
2043 assertNull(dpm.getShortSupportMessageForUser(admin1,
2044 DpmMockContext.CALLER_USER_HANDLE));
2045 mMockContext.binder.callingUid = DpmMockContext.CALLER_UID;
2046
2047 dpm.setLongSupportMessage(admin1, null);
2048 assertNull(dpm.getLongSupportMessage(admin1));
2049 }
2050 }
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002051
phweiss73145f42017-01-17 19:06:38 +01002052 public void testCreateAdminSupportIntent() throws Exception {
2053 // Setup device owner.
2054 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2055 setupDeviceOwner();
2056
2057 // Nonexisting permission returns null
2058 Intent intent = dpm.createAdminSupportIntent("disallow_nothing");
2059 assertNull(intent);
2060
2061 // Existing permission that is not set returns null
2062 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2063 assertNull(intent);
2064
2065 // Existing permission that is not set by device/profile owner returns null
2066 when(mContext.userManager.hasUserRestriction(
2067 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2068 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2069 .thenReturn(true);
2070 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2071 assertNull(intent);
2072
2073 // Permission that is set by device owner returns correct intent
2074 when(mContext.userManager.getUserRestrictionSource(
2075 eq(UserManager.DISALLOW_ADJUST_VOLUME),
2076 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2077 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2078 intent = dpm.createAdminSupportIntent(UserManager.DISALLOW_ADJUST_VOLUME);
2079 assertNotNull(intent);
2080 assertEquals(Settings.ACTION_SHOW_ADMIN_SUPPORT_DETAILS, intent.getAction());
2081 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2082 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2083 assertEquals(admin1,
2084 (ComponentName) intent.getParcelableExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN));
2085 assertEquals(UserManager.DISALLOW_ADJUST_VOLUME,
2086 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2087
2088 // Try with POLICY_DISABLE_CAMERA and POLICY_DISABLE_SCREEN_CAPTURE, which are not
2089 // user restrictions
2090
2091 // Camera is not disabled
2092 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2093 assertNull(intent);
2094
2095 // Camera is disabled
2096 dpm.setCameraDisabled(admin1, true);
2097 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2098 assertNotNull(intent);
2099 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2100 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2101
2102 // Screen capture is not disabled
2103 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2104 assertNull(intent);
2105
2106 // Screen capture is disabled
2107 dpm.setScreenCaptureDisabled(admin1, true);
2108 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2109 assertNotNull(intent);
2110 assertEquals(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE,
2111 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2112
2113 // Same checks for different user
2114 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2115 // Camera should be disabled by device owner
2116 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_CAMERA);
2117 assertNotNull(intent);
2118 assertEquals(DevicePolicyManager.POLICY_DISABLE_CAMERA,
2119 intent.getStringExtra(DevicePolicyManager.EXTRA_RESTRICTION));
2120 assertEquals(UserHandle.getUserId(DpmMockContext.CALLER_SYSTEM_USER_UID),
2121 intent.getIntExtra(Intent.EXTRA_USER_ID, -1));
2122 // ScreenCapture should not be disabled by device owner
2123 intent = dpm.createAdminSupportIntent(DevicePolicyManager.POLICY_DISABLE_SCREEN_CAPTURE);
2124 assertNull(intent);
2125 }
2126
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002127 /**
2128 * Test for:
2129 * {@link DevicePolicyManager#setAffiliationIds}
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002130 * {@link DevicePolicyManager#getAffiliationIds}
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002131 * {@link DevicePolicyManager#isAffiliatedUser}
2132 */
2133 public void testUserAffiliation() throws Exception {
2134 mContext.callerPermissions.add(permission.MANAGE_DEVICE_ADMINS);
2135 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2136 mContext.callerPermissions.add(permission.INTERACT_ACROSS_USERS_FULL);
2137
2138 // Check that the system user is unaffiliated.
2139 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2140 assertFalse(dpm.isAffiliatedUser());
2141
2142 // Set a device owner on the system user. Check that the system user becomes affiliated.
2143 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2144 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2145 assertTrue(dpm.setDeviceOwner(admin1, "owner-name"));
2146 assertTrue(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002147 assertTrue(dpm.getAffiliationIds(admin1).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002148
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002149 // Install a profile owner. Check that the test user is unaffiliated.
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002150 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2151 setAsProfileOwner(admin2);
2152 assertFalse(dpm.isAffiliatedUser());
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002153 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002154
2155 // Have the profile owner specify a set of affiliation ids. Check that the test user remains
2156 // unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002157 final List<String> userAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002158 userAffiliationIds.add("red");
2159 userAffiliationIds.add("green");
2160 userAffiliationIds.add("blue");
2161 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002162 MoreAsserts.assertContentsInAnyOrder(dpm.getAffiliationIds(admin2), "red", "green", "blue");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002163 assertFalse(dpm.isAffiliatedUser());
2164
2165 // Have the device owner specify a set of affiliation ids that do not intersect with those
2166 // specified by the profile owner. Check that the test user remains unaffiliated.
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002167 final List<String> deviceAffiliationIds = new ArrayList<>();
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002168 deviceAffiliationIds.add("cyan");
2169 deviceAffiliationIds.add("yellow");
2170 deviceAffiliationIds.add("magenta");
2171 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2172 dpm.setAffiliationIds(admin1, deviceAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002173 MoreAsserts.assertContentsInAnyOrder(
2174 dpm.getAffiliationIds(admin1), "cyan", "yellow", "magenta");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002175 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
2176 assertFalse(dpm.isAffiliatedUser());
2177
2178 // Have the profile owner specify a set of affiliation ids that intersect with those
2179 // specified by the device owner. Check that the test user becomes affiliated.
2180 userAffiliationIds.add("yellow");
2181 dpm.setAffiliationIds(admin2, userAffiliationIds);
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002182 MoreAsserts.assertContentsInAnyOrder(
2183 dpm.getAffiliationIds(admin2), "red", "green", "blue", "yellow");
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002184 assertTrue(dpm.isAffiliatedUser());
2185
Esteban Talaverac9bb3782016-11-11 15:41:14 +00002186 // Clear affiliation ids for the profile owner. The user becomes unaffiliated.
2187 dpm.setAffiliationIds(admin2, Collections.emptyList());
2188 assertTrue(dpm.getAffiliationIds(admin2).isEmpty());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002189 assertFalse(dpm.isAffiliatedUser());
2190
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002191 // Set affiliation ids again, then clear PO to check that the user becomes unaffiliated
2192 dpm.setAffiliationIds(admin2, userAffiliationIds);
2193 assertTrue(dpm.isAffiliatedUser());
2194 dpm.clearProfileOwner(admin2);
2195 assertFalse(dpm.isAffiliatedUser());
2196
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002197 // Check that the system user remains affiliated.
2198 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2199 assertTrue(dpm.isAffiliatedUser());
Esteban Talaveraa7bd04e2017-02-02 18:28:04 +00002200
2201 // Clear the device owner - the user becomes unaffiliated.
2202 clearDeviceOwner();
2203 assertFalse(dpm.isAffiliatedUser());
Bartosz Fabianowski4c052f22016-01-25 14:18:43 +01002204 }
Alan Treadwayafad8782016-01-19 15:15:08 +00002205
2206 public void testGetUserProvisioningState_defaultResult() {
2207 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2208 }
2209
2210 public void testSetUserProvisioningState_permission() throws Exception {
2211 setupProfileOwner();
2212 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2213
2214 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2215 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2216 }
2217
2218 public void testSetUserProvisioningState_unprivileged() throws Exception {
2219 setupProfileOwner();
2220 try {
2221 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2222 DpmMockContext.CALLER_USER_HANDLE);
2223 fail("Expected SecurityException");
2224 } catch (SecurityException expected) {
2225 }
2226 }
2227
2228 public void testSetUserProvisioningState_noManagement() {
2229 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2230 try {
2231 dpm.setUserProvisioningState(DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2232 DpmMockContext.CALLER_USER_HANDLE);
2233 fail("IllegalStateException expected");
2234 } catch (IllegalStateException e) {
2235 MoreAsserts.assertContainsRegex("change provisioning state unless a .* owner is set",
2236 e.getMessage());
2237 }
2238 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2239 }
2240
2241 public void testSetUserProvisioningState_deviceOwnerFromSetupWizard() throws Exception {
2242 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2243 setupDeviceOwner();
2244 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2245
2246 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2247 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2248 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2249 }
2250
2251 public void testSetUserProvisioningState_deviceOwnerFromSetupWizardAlternative()
2252 throws Exception {
2253 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2254 setupDeviceOwner();
2255 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2256
2257 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2258 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2259 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2260 }
2261
2262 public void testSetUserProvisioningState_deviceOwnerWithoutSetupWizard() throws Exception {
2263 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2264 setupDeviceOwner();
2265 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2266
2267 exerciseUserProvisioningTransitions(UserHandle.USER_SYSTEM,
2268 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2269 }
2270
2271 public void testSetUserProvisioningState_managedProfileFromSetupWizard_primaryUser()
2272 throws Exception {
2273 setupProfileOwner();
2274 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2275
2276 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2277 DevicePolicyManager.STATE_USER_PROFILE_COMPLETE,
2278 DevicePolicyManager.STATE_USER_UNMANAGED);
2279 }
2280
2281 public void testSetUserProvisioningState_managedProfileFromSetupWizard_managedProfile()
2282 throws Exception {
2283 setupProfileOwner();
2284 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2285
2286 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2287 DevicePolicyManager.STATE_USER_SETUP_COMPLETE,
2288 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2289 }
2290
2291 public void testSetUserProvisioningState_managedProfileWithoutSetupWizard() throws Exception {
2292 setupProfileOwner();
2293 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2294
2295 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2296 DevicePolicyManager.STATE_USER_SETUP_FINALIZED);
2297 }
2298
2299 public void testSetUserProvisioningState_illegalTransitionOutOfFinalized1() throws Exception {
2300 setupProfileOwner();
2301 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2302
2303 try {
2304 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2305 DevicePolicyManager.STATE_USER_SETUP_FINALIZED,
2306 DevicePolicyManager.STATE_USER_UNMANAGED);
2307 fail("Expected IllegalStateException");
2308 } catch (IllegalStateException e) {
2309 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2310 e.getMessage());
2311 }
2312 }
2313
2314 public void testSetUserProvisioningState_illegalTransitionToAnotherInProgressState()
2315 throws Exception {
2316 setupProfileOwner();
2317 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2318
2319 try {
2320 exerciseUserProvisioningTransitions(DpmMockContext.CALLER_USER_HANDLE,
2321 DevicePolicyManager.STATE_USER_SETUP_INCOMPLETE,
2322 DevicePolicyManager.STATE_USER_SETUP_COMPLETE);
2323 fail("Expected IllegalStateException");
2324 } catch (IllegalStateException e) {
2325 MoreAsserts.assertContainsRegex("Cannot move to user provisioning state",
2326 e.getMessage());
2327 }
2328 }
2329
2330 private void exerciseUserProvisioningTransitions(int userId, int... states) {
2331 assertEquals(DevicePolicyManager.STATE_USER_UNMANAGED, dpm.getUserProvisioningState());
2332 for (int state : states) {
2333 dpm.setUserProvisioningState(state, userId);
2334 assertEquals(state, dpm.getUserProvisioningState());
2335 }
2336 }
2337
2338 private void setupProfileOwner() throws Exception {
2339 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2340
2341 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_UID);
2342 dpm.setActiveAdmin(admin1, false);
2343 assertTrue(dpm.setProfileOwner(admin1, null, DpmMockContext.CALLER_USER_HANDLE));
2344
2345 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2346 }
2347
2348 private void setupDeviceOwner() throws Exception {
2349 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
2350
2351 setUpPackageManagerForAdmin(admin1, DpmMockContext.CALLER_SYSTEM_USER_UID);
2352 dpm.setActiveAdmin(admin1, false);
2353 assertTrue(dpm.setDeviceOwner(admin1, null, UserHandle.USER_SYSTEM));
2354
2355 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
2356 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002357
2358 public void testSetMaximumTimeToLock() {
2359 mContext.callerPermissions.add(android.Manifest.permission.MANAGE_DEVICE_ADMINS);
2360
2361 dpm.setActiveAdmin(admin1, /* replace =*/ false);
2362 dpm.setActiveAdmin(admin2, /* replace =*/ false);
2363
2364 reset(mMockContext.powerManagerInternal);
2365 reset(mMockContext.settings);
2366
2367 dpm.setMaximumTimeToLock(admin1, 0);
2368 verifyScreenTimeoutCall(null, false);
2369 reset(mMockContext.powerManagerInternal);
2370 reset(mMockContext.settings);
2371
2372 dpm.setMaximumTimeToLock(admin1, 1);
2373 verifyScreenTimeoutCall(1, true);
2374 reset(mMockContext.powerManagerInternal);
2375 reset(mMockContext.settings);
2376
2377 dpm.setMaximumTimeToLock(admin2, 10);
2378 verifyScreenTimeoutCall(null, false);
2379 reset(mMockContext.powerManagerInternal);
2380 reset(mMockContext.settings);
2381
2382 dpm.setMaximumTimeToLock(admin1, 5);
2383 verifyScreenTimeoutCall(5, true);
2384 reset(mMockContext.powerManagerInternal);
2385 reset(mMockContext.settings);
2386
2387 dpm.setMaximumTimeToLock(admin2, 4);
2388 verifyScreenTimeoutCall(4, true);
2389 reset(mMockContext.powerManagerInternal);
2390 reset(mMockContext.settings);
2391
2392 dpm.setMaximumTimeToLock(admin1, 0);
2393 reset(mMockContext.powerManagerInternal);
2394 reset(mMockContext.settings);
2395
2396 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE);
2397 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2398 reset(mMockContext.powerManagerInternal);
2399 reset(mMockContext.settings);
2400
2401 dpm.setMaximumTimeToLock(admin2, Integer.MAX_VALUE + 1);
2402 verifyScreenTimeoutCall(Integer.MAX_VALUE, true);
2403 reset(mMockContext.powerManagerInternal);
2404 reset(mMockContext.settings);
2405
2406 dpm.setMaximumTimeToLock(admin2, 10);
2407 verifyScreenTimeoutCall(10, true);
2408 reset(mMockContext.powerManagerInternal);
2409 reset(mMockContext.settings);
2410
2411 // There's no restriction; shold be set to MAX.
2412 dpm.setMaximumTimeToLock(admin2, 0);
2413 verifyScreenTimeoutCall(Integer.MAX_VALUE, false);
2414 }
2415
Michal Karpinski943aabd2016-10-06 11:09:25 +01002416 public void testSetRequiredStrongAuthTimeout_DeviceOwner() throws Exception {
2417 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
2418 setupDeviceOwner();
2419 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2420
Michal Karpinskid084ca52017-01-18 15:54:18 +00002421 final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);
2422 final long ONE_MINUTE = TimeUnit.MINUTES.toMillis(1);
2423 final long MIN_PLUS_ONE_MINUTE = MINIMUM_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE;
2424 final long MAX_MINUS_ONE_MINUTE = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS
2425 - ONE_MINUTE;
2426
2427 // verify that the minimum timeout cannot be modified on user builds (system property is
2428 // not being read)
2429 mContext.buildMock.isDebuggable = false;
2430
2431 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2432 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2433 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
2434
2435 verify(mContext.systemProperties, never()).getLong(anyString(), anyLong());
2436
2437 // restore to the debuggable build state
2438 mContext.buildMock.isDebuggable = true;
2439
2440 // Always return the default (second arg) when getting system property for long type
2441 when(mContext.systemProperties.getLong(anyString(), anyLong())).thenAnswer(
2442 new Answer<Long>() {
2443 @Override
2444 public Long answer(InvocationOnMock invocation) throws Throwable {
2445 return (Long) invocation.getArguments()[1];
2446 }
2447 }
2448 );
2449
2450 // reset to default (0 means the admin is not participating, so default should be returned)
2451 dpm.setRequiredStrongAuthTimeout(admin1, 0);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002452
2453 // aggregation should be the default if unset by any admin
2454 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2455 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2456
2457 // admin not participating by default
2458 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2459
2460 //clamping from the top
2461 dpm.setRequiredStrongAuthTimeout(admin1,
2462 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS + ONE_MINUTE);
2463 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1),
2464 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2465 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2466 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2467
Michal Karpinskid084ca52017-01-18 15:54:18 +00002468 // 0 means the admin is not participating, so default should be returned
Michal Karpinski943aabd2016-10-06 11:09:25 +01002469 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2470 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2471 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2472 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2473
2474 // clamping from the bottom
2475 dpm.setRequiredStrongAuthTimeout(admin1, MINIMUM_STRONG_AUTH_TIMEOUT_MS - ONE_MINUTE);
2476 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2477 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MINIMUM_STRONG_AUTH_TIMEOUT_MS);
2478
Michal Karpinskid084ca52017-01-18 15:54:18 +00002479 // values within range
2480 dpm.setRequiredStrongAuthTimeout(admin1, MIN_PLUS_ONE_MINUTE);
2481 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MIN_PLUS_ONE_MINUTE);
2482 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MIN_PLUS_ONE_MINUTE);
2483
2484 dpm.setRequiredStrongAuthTimeout(admin1, MAX_MINUS_ONE_MINUTE);
2485 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), MAX_MINUS_ONE_MINUTE);
2486 assertEquals(dpm.getRequiredStrongAuthTimeout(null), MAX_MINUS_ONE_MINUTE);
Michal Karpinski943aabd2016-10-06 11:09:25 +01002487
2488 // reset to default
2489 dpm.setRequiredStrongAuthTimeout(admin1, 0);
2490 assertEquals(dpm.getRequiredStrongAuthTimeout(admin1), 0);
2491 assertEquals(dpm.getRequiredStrongAuthTimeout(null),
2492 DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS);
2493
2494 // negative value
2495 try {
2496 dpm.setRequiredStrongAuthTimeout(admin1, -ONE_MINUTE);
2497 fail("Didn't throw IllegalArgumentException");
2498 } catch (IllegalArgumentException iae) {
2499 }
2500 }
2501
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002502 private void verifyScreenTimeoutCall(Integer expectedTimeout,
2503 boolean shouldStayOnWhilePluggedInBeCleared) {
2504 if (expectedTimeout == null) {
2505 verify(mMockContext.powerManagerInternal, times(0))
2506 .setMaximumScreenOffTimeoutFromDeviceAdmin(anyInt());
2507 } else {
2508 verify(mMockContext.powerManagerInternal, times(1))
2509 .setMaximumScreenOffTimeoutFromDeviceAdmin(eq(expectedTimeout));
2510 }
2511 // TODO Verify calls to settingsGlobalPutInt. Tried but somehow mockito threw
2512 // UnfinishedVerificationException.
2513 }
Makoto Onuki2a3c3da2016-02-18 14:25:30 -08002514
Esteban Talavera01576862016-12-15 11:16:44 +00002515 private void setup_DeviceAdminFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002516 when(mContext.packageManager.hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN))
2517 .thenReturn(false);
2518 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2519 .thenReturn(false);
2520 initializeDpms();
2521 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2522 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2523 .thenReturn(true);
2524 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2525
2526 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002527 }
Victor Chang3e794af2016-03-04 13:48:17 +00002528
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002529 public void testIsProvisioningAllowed_DeviceAdminFeatureOff() throws Exception {
2530 setup_DeviceAdminFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002531 mContext.packageName = admin1.getPackageName();
2532 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002533 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
2534 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2535 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2536 false);
2537 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2538 }
2539
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002540 public void testCheckProvisioningPreCondition_DeviceAdminFeatureOff() throws Exception {
2541 setup_DeviceAdminFeatureOff();
2542 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2543 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2544 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2545 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2546 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2547 assertCheckProvisioningPreCondition(
2548 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2549 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2550 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2551 DevicePolicyManager.CODE_DEVICE_ADMIN_NOT_SUPPORTED);
2552 }
2553
Esteban Talavera01576862016-12-15 11:16:44 +00002554 private void setup_ManagedProfileFeatureOff() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002555 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2556 .thenReturn(false);
2557 initializeDpms();
2558 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2559 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2560 .thenReturn(true);
2561 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2562
2563 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002564 }
Victor Chang3e794af2016-03-04 13:48:17 +00002565
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002566 public void testIsProvisioningAllowed_ManagedProfileFeatureOff() throws Exception {
2567 setup_ManagedProfileFeatureOff();
Esteban Talavera01576862016-12-15 11:16:44 +00002568 mContext.packageName = admin1.getPackageName();
2569 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002570 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2571 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2572 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2573 false);
2574 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2575
2576 // Test again when split user is on
2577 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2578 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2579 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2580 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2581 true);
2582 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, false);
2583 }
2584
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002585 public void testCheckProvisioningPreCondition_ManagedProfileFeatureOff() throws Exception {
2586 setup_ManagedProfileFeatureOff();
2587 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2588 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2589 DevicePolicyManager.CODE_OK);
2590 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2591 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2592 assertCheckProvisioningPreCondition(
2593 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2594 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2595 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2596 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2597
2598 // Test again when split user is on
2599 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2600 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2601 DevicePolicyManager.CODE_OK);
2602 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2603 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2604 assertCheckProvisioningPreCondition(
2605 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2606 DevicePolicyManager.CODE_OK);
2607 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2608 DevicePolicyManager.CODE_MANAGED_USERS_NOT_SUPPORTED);
2609 }
2610
Esteban Talavera01576862016-12-15 11:16:44 +00002611 private void setup_nonSplitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002612 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2613 .thenReturn(true);
2614 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2615 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2616 .thenReturn(true);
2617 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2618
2619 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002620 }
Victor Chang3e794af2016-03-04 13:48:17 +00002621
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002622 public void testIsProvisioningAllowed_nonSplitUser_firstBoot_primaryUser() throws Exception {
2623 setup_nonSplitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002624 mContext.packageName = admin1.getPackageName();
2625 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002626 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2627 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2628 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2629 false /* because of non-split user */);
2630 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2631 false /* because of non-split user */);
2632 }
2633
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002634 public void testCheckProvisioningPreCondition_nonSplitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002635 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002636 setup_nonSplitUser_firstBoot_primaryUser();
2637 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2638 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2639 DevicePolicyManager.CODE_OK);
2640 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2641 DevicePolicyManager.CODE_OK);
2642 assertCheckProvisioningPreCondition(
2643 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2644 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2645 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2646 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2647 }
2648
Esteban Talavera01576862016-12-15 11:16:44 +00002649 private void setup_nonSplitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002650 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2651 .thenReturn(true);
2652 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(false);
2653 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2654 .thenReturn(true);
2655 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2656
2657 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002658 }
Victor Chang3e794af2016-03-04 13:48:17 +00002659
Nicolas Prevot45d29072017-01-18 16:11:19 +00002660 private void setup_nonSplitUser_withDo_primaryUser() throws Exception {
2661 setDeviceOwner();
2662 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2663 setUpPackageManagerForFakeAdmin(adminAnotherPackage, DpmMockContext.ANOTHER_UID, admin2);
2664 }
2665
2666 private void setup_nonSplitUser_withDo_primaryUser_ManagedProfile() throws Exception {
2667 setup_nonSplitUser_withDo_primaryUser();
2668 final int MANAGED_PROFILE_USER_ID = 18;
2669 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 1308);
2670 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
2671 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2672 false /* we can't remove a managed profile */)).thenReturn(false);
2673 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM,
2674 true)).thenReturn(true);
2675 }
2676
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002677 public void testIsProvisioningAllowed_nonSplitUser_afterDeviceSetup_primaryUser()
2678 throws Exception {
2679 setup_nonSplitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002680 mContext.packageName = admin1.getPackageName();
2681 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002682 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2683 false/* because of completed device setup */);
2684 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2685 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2686 false/* because of non-split user */);
2687 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2688 false/* because of non-split user */);
2689 }
2690
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002691 public void testCheckProvisioningPreCondition_nonSplitUser_afterDeviceSetup_primaryUser()
2692 throws Exception {
2693 setup_nonSplitUser_afterDeviceSetup_primaryUser();
2694 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2695 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2696 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2697 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2698 DevicePolicyManager.CODE_OK);
2699 assertCheckProvisioningPreCondition(
2700 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2701 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2702 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2703 DevicePolicyManager.CODE_NOT_SYSTEM_USER_SPLIT);
2704 }
2705
Nicolas Prevot45d29072017-01-18 16:11:19 +00002706 public void testProvisioning_nonSplitUser_withDo_primaryUser() throws Exception {
2707 setup_nonSplitUser_withDo_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002708 mContext.packageName = admin1.getPackageName();
Esteban Talavera01576862016-12-15 11:16:44 +00002709 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2710
2711 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2712 DevicePolicyManager.CODE_HAS_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002713 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, false);
Esteban Talavera01576862016-12-15 11:16:44 +00002714
2715 // COMP mode is allowed.
2716 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2717 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002718 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002719
Nicolas Prevot45d29072017-01-18 16:11:19 +00002720 // And other DPCs can also provision a managed profile (DO + BYOD case).
Esteban Talavera01576862016-12-15 11:16:44 +00002721 assertCheckProvisioningPreCondition(
2722 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002723 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002724 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002725 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2726 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2727 }
Esteban Talavera01576862016-12-15 11:16:44 +00002728
Nicolas Prevot45d29072017-01-18 16:11:19 +00002729 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedByDo() throws Exception {
2730 setup_nonSplitUser_withDo_primaryUser();
2731 mContext.packageName = admin1.getPackageName();
2732 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2733 // The DO should be allowed to initiate provisioning if it set the restriction itself, but
2734 // other packages should be forbidden.
Esteban Talavera01576862016-12-15 11:16:44 +00002735 when(mContext.userManager.hasUserRestriction(
2736 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2737 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2738 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002739 when(mContext.userManager.getUserRestrictionSource(
2740 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2741 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2742 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
2743 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2744 DevicePolicyManager.CODE_OK);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002745 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002746 assertCheckProvisioningPreCondition(
2747 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002748 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002749 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002750 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2751 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2752 }
Esteban Talavera01576862016-12-15 11:16:44 +00002753
Nicolas Prevot45d29072017-01-18 16:11:19 +00002754 public void testProvisioning_nonSplitUser_withDo_primaryUser_restrictedBySystem()
2755 throws Exception {
2756 setup_nonSplitUser_withDo_primaryUser();
2757 mContext.packageName = admin1.getPackageName();
2758 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00002759 // The DO should not be allowed to initiate provisioning if the restriction is set by
2760 // another entity.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002761 when(mContext.userManager.hasUserRestriction(
2762 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2763 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2764 .thenReturn(true);
Esteban Talavera01576862016-12-15 11:16:44 +00002765 when(mContext.userManager.getUserRestrictionSource(
2766 eq(UserManager.DISALLOW_ADD_MANAGED_PROFILE),
2767 eq(UserHandle.getUserHandleForUid(mContext.binder.callingUid))))
2768 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
2769 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2770 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002771 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
2772
2773 assertCheckProvisioningPreCondition(
Esteban Talavera01576862016-12-15 11:16:44 +00002774 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Nicolas Prevot45d29072017-01-18 16:11:19 +00002775 DpmMockContext.ANOTHER_PACKAGE_NAME,
Esteban Talavera01576862016-12-15 11:16:44 +00002776 DevicePolicyManager.CODE_ADD_MANAGED_PROFILE_DISALLOWED);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002777 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2778 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2779 }
2780
2781 public void testCheckProvisioningPreCondition_nonSplitUser_comp() throws Exception {
2782 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2783 mContext.packageName = admin1.getPackageName();
2784 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2785
2786 // We can delete the managed profile to create a new one, so provisioning is allowed.
2787 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2788 DevicePolicyManager.CODE_OK);
2789 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2790 assertCheckProvisioningPreCondition(
2791 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2792 DpmMockContext.ANOTHER_PACKAGE_NAME,
2793 DevicePolicyManager.CODE_OK);
2794 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true,
2795 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
2796 }
2797
2798 public void testCheckProvisioningPreCondition_nonSplitUser_comp_cannot_remove_profile()
2799 throws Exception {
2800 setup_nonSplitUser_withDo_primaryUser_ManagedProfile();
2801 mContext.packageName = admin1.getPackageName();
2802 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2803 when(mContext.userManager.hasUserRestriction(
2804 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2805 eq(UserHandle.SYSTEM)))
2806 .thenReturn(true);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002807 when(mContext.userManager.getUserRestrictionSource(
2808 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
2809 eq(UserHandle.SYSTEM)))
2810 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
Nicolas Prevot45d29072017-01-18 16:11:19 +00002811
2812 // We can't remove the profile to create a new one.
Nicolas Prevot45d29072017-01-18 16:11:19 +00002813 assertCheckProvisioningPreCondition(
2814 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2815 DpmMockContext.ANOTHER_PACKAGE_NAME,
2816 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
2817 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false,
2818 DpmMockContext.ANOTHER_PACKAGE_NAME, DpmMockContext.ANOTHER_UID);
Nicolas Prevotd37c4a92017-01-23 11:56:00 +00002819
2820 // But the device owner can still do it because it has set the restriction itself.
2821 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2822 DevicePolicyManager.CODE_OK);
2823 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
Esteban Talavera01576862016-12-15 11:16:44 +00002824 }
2825
2826 private void setup_splitUser_firstBoot_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002827 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2828 .thenReturn(true);
2829 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2830 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2831 .thenReturn(false);
2832 setUserSetupCompleteForUser(false, UserHandle.USER_SYSTEM);
2833
2834 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002835 }
Victor Chang3e794af2016-03-04 13:48:17 +00002836
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002837 public void testIsProvisioningAllowed_splitUser_firstBoot_systemUser() throws Exception {
2838 setup_splitUser_firstBoot_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002839 mContext.packageName = admin1.getPackageName();
2840 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002841 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2842 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2843 false /* because canAddMoreManagedProfiles returns false */);
2844 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2845 true);
2846 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2847 false/* because calling uid is system user */);
Victor Chang3e794af2016-03-04 13:48:17 +00002848 }
2849
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002850 public void testCheckProvisioningPreCondition_splitUser_firstBoot_systemUser()
2851 throws Exception {
2852 setup_splitUser_firstBoot_systemUser();
2853 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2854 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2855 DevicePolicyManager.CODE_OK);
2856 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002857 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002858 assertCheckProvisioningPreCondition(
2859 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2860 DevicePolicyManager.CODE_OK);
2861 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2862 DevicePolicyManager.CODE_SYSTEM_USER);
2863 }
2864
Esteban Talavera01576862016-12-15 11:16:44 +00002865 private void setup_splitUser_afterDeviceSetup_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002866 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2867 .thenReturn(true);
2868 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2869 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2870 .thenReturn(false);
2871 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2872
2873 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002874 }
Victor Chang3e794af2016-03-04 13:48:17 +00002875
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002876 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_systemUser() throws Exception {
2877 setup_splitUser_afterDeviceSetup_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002878 mContext.packageName = admin1.getPackageName();
2879 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002880 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2881 true/* it's undefined behavior. Can be changed into false in the future */);
2882 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2883 false /* because canAddMoreManagedProfiles returns false */);
2884 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2885 true/* it's undefined behavior. Can be changed into false in the future */);
2886 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2887 false/* because calling uid is system user */);
2888 }
2889
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002890 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_systemUser()
2891 throws Exception {
2892 setup_splitUser_afterDeviceSetup_systemUser();
2893 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2894 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2895 DevicePolicyManager.CODE_OK);
2896 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
Esteban Talavera6c9116a2016-11-24 16:12:44 +00002897 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002898 assertCheckProvisioningPreCondition(
2899 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2900 DevicePolicyManager.CODE_OK);
2901 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2902 DevicePolicyManager.CODE_SYSTEM_USER);
2903 }
2904
Esteban Talavera01576862016-12-15 11:16:44 +00002905 private void setup_splitUser_firstBoot_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002906 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2907 .thenReturn(true);
2908 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2909 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2910 true)).thenReturn(true);
2911 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
2912
2913 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002914 }
Victor Chang3e794af2016-03-04 13:48:17 +00002915
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002916 public void testIsProvisioningAllowed_splitUser_firstBoot_primaryUser() throws Exception {
2917 setup_splitUser_firstBoot_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002918 mContext.packageName = admin1.getPackageName();
2919 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002920 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, true);
2921 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2922 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2923 true);
2924 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER, true);
Victor Chang3e794af2016-03-04 13:48:17 +00002925 }
2926
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002927 public void testCheckProvisioningPreCondition_splitUser_firstBoot_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002928 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002929 setup_splitUser_firstBoot_primaryUser();
2930 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2931 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2932 DevicePolicyManager.CODE_OK);
2933 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2934 DevicePolicyManager.CODE_OK);
2935 assertCheckProvisioningPreCondition(
2936 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2937 DevicePolicyManager.CODE_OK);
2938 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2939 DevicePolicyManager.CODE_OK);
2940 }
2941
Esteban Talavera01576862016-12-15 11:16:44 +00002942 private void setup_splitUser_afterDeviceSetup_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002943 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2944 .thenReturn(true);
2945 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2946 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
2947 true)).thenReturn(true);
2948 setUserSetupCompleteForUser(true, DpmMockContext.CALLER_USER_HANDLE);
2949
2950 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002951 }
Victor Chang3e794af2016-03-04 13:48:17 +00002952
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002953 public void testIsProvisioningAllowed_splitUser_afterDeviceSetup_primaryUser()
2954 throws Exception {
2955 setup_splitUser_afterDeviceSetup_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002956 mContext.packageName = admin1.getPackageName();
2957 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00002958 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2959 true/* it's undefined behavior. Can be changed into false in the future */);
2960 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
2961 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2962 true/* it's undefined behavior. Can be changed into false in the future */);
2963 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2964 false/* because user setup completed */);
2965 }
2966
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002967 public void testCheckProvisioningPreCondition_splitUser_afterDeviceSetup_primaryUser()
Victor Chang3e794af2016-03-04 13:48:17 +00002968 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002969 setup_splitUser_afterDeviceSetup_primaryUser();
2970 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
2971 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE,
2972 DevicePolicyManager.CODE_OK);
2973 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
2974 DevicePolicyManager.CODE_OK);
2975 assertCheckProvisioningPreCondition(
2976 DevicePolicyManager.ACTION_PROVISION_MANAGED_SHAREABLE_DEVICE,
2977 DevicePolicyManager.CODE_OK);
2978 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_USER,
2979 DevicePolicyManager.CODE_USER_SETUP_COMPLETED);
2980 }
2981
Esteban Talavera01576862016-12-15 11:16:44 +00002982 private void setup_provisionManagedProfileWithDeviceOwner_systemUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00002983 setDeviceOwner();
2984
2985 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
2986 .thenReturn(true);
2987 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
2988 when(mContext.userManager.canAddMoreManagedProfiles(UserHandle.USER_SYSTEM, true))
2989 .thenReturn(false);
2990 setUserSetupCompleteForUser(true, UserHandle.USER_SYSTEM);
2991
2992 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002993 }
Victor Chang3e794af2016-03-04 13:48:17 +00002994
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00002995 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_systemUser()
2996 throws Exception {
2997 setup_provisionManagedProfileWithDeviceOwner_systemUser();
Esteban Talavera01576862016-12-15 11:16:44 +00002998 mContext.packageName = admin1.getPackageName();
2999 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Victor Chang3e794af2016-03-04 13:48:17 +00003000 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3001 false /* can't provision managed profile on system user */);
3002 }
3003
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003004 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_systemUser()
Victor Chang3e794af2016-03-04 13:48:17 +00003005 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003006 setup_provisionManagedProfileWithDeviceOwner_systemUser();
3007 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3008 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3009 DevicePolicyManager.CODE_SPLIT_SYSTEM_USER_DEVICE_SYSTEM_USER);
3010 }
3011
3012 private void setup_provisionManagedProfileWithDeviceOwner_primaryUser() throws Exception {
Victor Chang3e794af2016-03-04 13:48:17 +00003013 setDeviceOwner();
3014
3015 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3016 .thenReturn(true);
3017 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
3018 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3019 true)).thenReturn(true);
3020 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3021
3022 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003023 }
Victor Chang3e794af2016-03-04 13:48:17 +00003024
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003025 public void testIsProvisioningAllowed_provisionManagedProfileWithDeviceOwner_primaryUser()
3026 throws Exception {
3027 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003028 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
3029 mContext.packageName = admin1.getPackageName();
Victor Chang3e794af2016-03-04 13:48:17 +00003030 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, true);
3031 }
3032
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003033 public void testCheckProvisioningPreCondition_provisionManagedProfileWithDeviceOwner_primaryUser()
Nicolas Prevot56400a42016-11-10 12:57:54 +00003034 throws Exception {
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003035 setup_provisionManagedProfileWithDeviceOwner_primaryUser();
3036 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
Esteban Talavera01576862016-12-15 11:16:44 +00003037
3038 // COMP mode is allowed.
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003039 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3040 DevicePolicyManager.CODE_OK);
3041 }
3042
3043 private void setup_provisionManagedProfileCantRemoveUser_primaryUser() throws Exception {
Nicolas Prevot56400a42016-11-10 12:57:54 +00003044 setDeviceOwner();
3045
3046 when(mContext.ipackageManager.hasSystemFeature(PackageManager.FEATURE_MANAGED_USERS, 0))
3047 .thenReturn(true);
3048 when(mContext.userManagerForMock.isSplitSystemUser()).thenReturn(true);
Esteban Talavera6c9116a2016-11-24 16:12:44 +00003049 when(mContext.userManager.hasUserRestriction(
Esteban Talavera01576862016-12-15 11:16:44 +00003050 eq(UserManager.DISALLOW_REMOVE_MANAGED_PROFILE),
3051 eq(UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))))
Nicolas Prevot56400a42016-11-10 12:57:54 +00003052 .thenReturn(true);
3053 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003054 false /* we can't remove a managed profile */)).thenReturn(false);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003055 when(mContext.userManager.canAddMoreManagedProfiles(DpmMockContext.CALLER_USER_HANDLE,
3056 true)).thenReturn(true);
3057 setUserSetupCompleteForUser(false, DpmMockContext.CALLER_USER_HANDLE);
3058
3059 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003060 }
Nicolas Prevot56400a42016-11-10 12:57:54 +00003061
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003062 public void testIsProvisioningAllowed_provisionManagedProfileCantRemoveUser_primaryUser()
3063 throws Exception {
3064 setup_provisionManagedProfileCantRemoveUser_primaryUser();
Esteban Talavera01576862016-12-15 11:16:44 +00003065 mContext.packageName = admin1.getPackageName();
3066 setUpPackageManagerForAdmin(admin1, mContext.binder.callingUid);
Nicolas Prevot56400a42016-11-10 12:57:54 +00003067 assertProvisioningAllowed(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, false);
3068 }
3069
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003070 public void testCheckProvisioningPreCondition_provisionManagedProfileCantRemoveUser_primaryUser()
3071 throws Exception {
3072 setup_provisionManagedProfileCantRemoveUser_primaryUser();
3073 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3074 assertCheckProvisioningPreCondition(DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE,
3075 DevicePolicyManager.CODE_CANNOT_ADD_MANAGED_PROFILE);
3076 }
3077
3078 public void testCheckProvisioningPreCondition_permission() {
3079 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3080 try {
Esteban Talavera01576862016-12-15 11:16:44 +00003081 dpm.checkProvisioningPreCondition(
3082 DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE, "some.package");
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00003083 fail("Didn't throw SecurityException");
3084 } catch (SecurityException expected) {
3085 }
3086 }
3087
Victor Chang3577ed22016-08-25 18:49:26 +01003088 public void testForceUpdateUserSetupComplete_permission() {
3089 // GIVEN the permission MANAGE_PROFILE_AND_DEVICE_OWNERS is not granted
3090 try {
3091 dpm.forceUpdateUserSetupComplete();
3092 fail("Didn't throw SecurityException");
3093 } catch (SecurityException expected) {
3094 }
3095 }
3096
3097 public void testForceUpdateUserSetupComplete_systemUser() {
3098 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3099 // GIVEN calling from user 20
3100 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3101 try {
3102 dpm.forceUpdateUserSetupComplete();
3103 fail("Didn't throw SecurityException");
3104 } catch (SecurityException expected) {
3105 }
3106 }
3107
3108 public void testForceUpdateUserSetupComplete_userbuild() {
3109 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3110 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3111
3112 final int userId = UserHandle.USER_SYSTEM;
3113 // GIVEN userComplete is false in SettingsProvider
3114 setUserSetupCompleteForUser(false, userId);
3115
3116 // GIVEN userComplete is true in DPM
3117 DevicePolicyManagerService.DevicePolicyData userData =
3118 new DevicePolicyManagerService.DevicePolicyData(userId);
3119 userData.mUserSetupComplete = true;
3120 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3121
3122 // GIVEN it's user build
3123 mContext.buildMock.isDebuggable = false;
3124
3125 assertTrue(dpms.hasUserSetupCompleted());
3126
3127 dpm.forceUpdateUserSetupComplete();
3128
3129 // THEN the state in dpms is not changed
3130 assertTrue(dpms.hasUserSetupCompleted());
3131 }
3132
3133 public void testForceUpdateUserSetupComplete_userDebugbuild() {
3134 mContext.callerPermissions.add(permission.MANAGE_PROFILE_AND_DEVICE_OWNERS);
3135 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3136
3137 final int userId = UserHandle.USER_SYSTEM;
3138 // GIVEN userComplete is false in SettingsProvider
3139 setUserSetupCompleteForUser(false, userId);
3140
3141 // GIVEN userComplete is true in DPM
3142 DevicePolicyManagerService.DevicePolicyData userData =
3143 new DevicePolicyManagerService.DevicePolicyData(userId);
3144 userData.mUserSetupComplete = true;
3145 dpms.mUserData.put(UserHandle.USER_SYSTEM, userData);
3146
3147 // GIVEN it's userdebug build
3148 mContext.buildMock.isDebuggable = true;
3149
3150 assertTrue(dpms.hasUserSetupCompleted());
3151
3152 dpm.forceUpdateUserSetupComplete();
3153
3154 // THEN the state in dpms is not changed
3155 assertFalse(dpms.hasUserSetupCompleted());
3156 }
3157
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003158 private void clearDeviceOwner() throws Exception {
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003159 final long ident = mContext.binder.clearCallingIdentity();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003160 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3161 doReturn(DpmMockContext.CALLER_SYSTEM_USER_UID).when(mContext.packageManager)
3162 .getPackageUidAsUser(eq(admin1.getPackageName()), anyInt());
3163 dpm.clearDeviceOwnerApp(admin1.getPackageName());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003164 mContext.binder.restoreCallingIdentity(ident);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003165 }
3166
3167 public void testGetLastSecurityLogRetrievalTime() throws Exception {
3168 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3169 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003170
3171 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3172 // feature is disabled because there are non-affiliated secondary users.
3173 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003174 when(mContext.resources.getBoolean(R.bool.config_supportPreRebootSecurityLogs))
3175 .thenReturn(true);
3176
3177 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003178 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003179
3180 // Enabling logging should not change the timestamp.
3181 dpm.setSecurityLoggingEnabled(admin1, true);
Esteban Talaverad36dd152016-12-15 08:51:45 +00003182 verify(mContext.settings)
3183 .securityLogSetLoggingEnabledProperty(true);
3184 when(mContext.settings.securityLogGetLoggingEnabledProperty())
3185 .thenReturn(true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003186 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003187
3188 // Retrieving the logs should update the timestamp.
3189 final long beforeRetrieval = System.currentTimeMillis();
3190 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003191 final long firstSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003192 final long afterRetrieval = System.currentTimeMillis();
3193 assertTrue(firstSecurityLogRetrievalTime >= beforeRetrieval);
3194 assertTrue(firstSecurityLogRetrievalTime <= afterRetrieval);
3195
3196 // Retrieving the pre-boot logs should update the timestamp.
3197 Thread.sleep(2);
3198 dpm.retrievePreRebootSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003199 final long secondSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003200 assertTrue(secondSecurityLogRetrievalTime > firstSecurityLogRetrievalTime);
3201
3202 // Checking the timestamp again should not change it.
3203 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003204 assertEquals(secondSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003205
3206 // Retrieving the logs again should update the timestamp.
3207 dpm.retrieveSecurityLogs(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003208 final long thirdSecurityLogRetrievalTime = dpm.getLastSecurityLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003209 assertTrue(thirdSecurityLogRetrievalTime > secondSecurityLogRetrievalTime);
3210
3211 // Disabling logging should not change the timestamp.
3212 Thread.sleep(2);
3213 dpm.setSecurityLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003214 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003215
3216 // Restarting the DPMS should not lose the timestamp.
3217 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003218 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003219
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003220 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3221 mContext.binder.callingUid = 1234567;
3222 mContext.callerPermissions.add(permission.MANAGE_USERS);
3223 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3224 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3225
3226 // System can retrieve the timestamp.
3227 mContext.binder.clearCallingIdentity();
3228 assertEquals(thirdSecurityLogRetrievalTime, dpm.getLastSecurityLogRetrievalTime());
3229
3230 // Removing the device owner should clear the timestamp.
3231 clearDeviceOwner();
3232 assertEquals(-1, dpm.getLastSecurityLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003233 }
3234
3235 public void testGetLastBugReportRequestTime() throws Exception {
3236 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3237 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003238
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003239 mContext.packageName = admin1.getPackageName();
3240 mContext.applicationInfo = new ApplicationInfo();
3241 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3242 .thenReturn(Color.WHITE);
3243 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3244 anyObject())).thenReturn(Color.WHITE);
3245
Esteban Talaverad36dd152016-12-15 08:51:45 +00003246 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3247 // feature is disabled because there are non-affiliated secondary users.
3248 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
3249
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003250 // No bug reports were requested so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003251 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003252
3253 // Requesting a bug report should update the timestamp.
3254 final long beforeRequest = System.currentTimeMillis();
3255 dpm.requestBugreport(admin1);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003256 final long bugReportRequestTime = dpm.getLastBugReportRequestTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003257 final long afterRequest = System.currentTimeMillis();
3258 assertTrue(bugReportRequestTime >= beforeRequest);
3259 assertTrue(bugReportRequestTime <= afterRequest);
3260
3261 // Checking the timestamp again should not change it.
3262 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003263 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003264
3265 // Restarting the DPMS should not lose the timestamp.
3266 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003267 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003268
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003269 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3270 mContext.binder.callingUid = 1234567;
3271 mContext.callerPermissions.add(permission.MANAGE_USERS);
3272 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3273 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3274
3275 // System can retrieve the timestamp.
3276 mContext.binder.clearCallingIdentity();
3277 assertEquals(bugReportRequestTime, dpm.getLastBugReportRequestTime());
3278
3279 // Removing the device owner should clear the timestamp.
3280 clearDeviceOwner();
3281 assertEquals(-1, dpm.getLastBugReportRequestTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003282 }
3283
3284 public void testGetLastNetworkLogRetrievalTime() throws Exception {
3285 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3286 setupDeviceOwner();
Esteban Talaverad36dd152016-12-15 08:51:45 +00003287 mContext.packageName = admin1.getPackageName();
3288 mContext.applicationInfo = new ApplicationInfo();
3289 when(mContext.resources.getColor(eq(R.color.notification_action_list), anyObject()))
3290 .thenReturn(Color.WHITE);
3291 when(mContext.resources.getColor(eq(R.color.notification_material_background_color),
3292 anyObject())).thenReturn(Color.WHITE);
3293
3294 // setUp() adds a secondary user for CALLER_USER_HANDLE. Remove it as otherwise the
3295 // feature is disabled because there are non-affiliated secondary users.
3296 mContext.removeUser(DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003297 when(mContext.iipConnectivityMetrics.registerNetdEventCallback(anyObject()))
3298 .thenReturn(true);
3299
3300 // No logs were retrieved so far.
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003301 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003302
3303 // Attempting to retrieve logs without enabling logging should not change the timestamp.
3304 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003305 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003306
3307 // Enabling logging should not change the timestamp.
3308 dpm.setNetworkLoggingEnabled(admin1, true);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003309 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003310
3311 // Retrieving the logs should update the timestamp.
3312 final long beforeRetrieval = System.currentTimeMillis();
3313 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003314 final long firstNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003315 final long afterRetrieval = System.currentTimeMillis();
3316 assertTrue(firstNetworkLogRetrievalTime >= beforeRetrieval);
3317 assertTrue(firstNetworkLogRetrievalTime <= afterRetrieval);
3318
3319 // Checking the timestamp again should not change it.
3320 Thread.sleep(2);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003321 assertEquals(firstNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003322
3323 // Retrieving the logs again should update the timestamp.
3324 dpm.retrieveNetworkLogs(admin1, 0 /* batchToken */);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003325 final long secondNetworkLogRetrievalTime = dpm.getLastNetworkLogRetrievalTime();
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003326 assertTrue(secondNetworkLogRetrievalTime > firstNetworkLogRetrievalTime);
3327
3328 // Disabling logging should not change the timestamp.
3329 Thread.sleep(2);
3330 dpm.setNetworkLoggingEnabled(admin1, false);
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003331 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003332
3333 // Restarting the DPMS should not lose the timestamp.
3334 initializeDpms();
Bartosz Fabianowski8d76e722016-11-25 12:36:20 +01003335 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3336
3337 // Any uid holding MANAGE_USERS permission can retrieve the timestamp.
3338 mContext.binder.callingUid = 1234567;
3339 mContext.callerPermissions.add(permission.MANAGE_USERS);
3340 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3341 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3342
3343 // System can retrieve the timestamp.
3344 mContext.binder.clearCallingIdentity();
3345 assertEquals(secondNetworkLogRetrievalTime, dpm.getLastNetworkLogRetrievalTime());
3346
3347 // Removing the device owner should clear the timestamp.
3348 clearDeviceOwner();
3349 assertEquals(-1, dpm.getLastNetworkLogRetrievalTime());
Bartosz Fabianowskib21b2412016-11-17 04:53:33 +01003350 }
3351
Tony Mak2f26b792016-11-28 17:54:51 +00003352 public void testGetBindDeviceAdminTargetUsers() throws Exception {
3353 // Setup device owner.
3354 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3355 setupDeviceOwner();
3356
3357 // Only device owner is setup, the result list should be empty.
3358 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3359 MoreAsserts.assertEmpty(targetUsers);
3360
3361 // Setup a managed profile managed by the same admin.
3362 final int MANAGED_PROFILE_USER_ID = 15;
3363 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3364 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3365
3366 // Add a secondary user, it should never talk with.
3367 final int ANOTHER_USER_ID = 36;
3368 mContext.addUser(ANOTHER_USER_ID, 0);
3369
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003370 // Since the managed profile is not affiliated, they should not be allowed to talk to each
3371 // other.
3372 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3373 MoreAsserts.assertEmpty(targetUsers);
3374
3375 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3376 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3377 MoreAsserts.assertEmpty(targetUsers);
3378
3379 // Setting affiliation ids
3380 final List<String> userAffiliationIds = Arrays.asList("some.affiliation-id");
3381 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3382 dpm.setAffiliationIds(admin1, userAffiliationIds);
3383
3384 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3385 dpm.setAffiliationIds(admin1, userAffiliationIds);
3386
Tony Mak2f26b792016-11-28 17:54:51 +00003387 // Calling from device owner admin, the result list should just contain the managed
3388 // profile user id.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003389 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003390 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3391 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.of(MANAGED_PROFILE_USER_ID));
3392
3393 // Calling from managed profile admin, the result list should just contain the system
3394 // user id.
3395 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3396 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3397 MoreAsserts.assertContentsInAnyOrder(targetUsers, UserHandle.SYSTEM);
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003398
3399 // Changing affiliation ids in one
3400 dpm.setAffiliationIds(admin1, Arrays.asList("some-different-affiliation-id"));
3401
3402 // Since the managed profile is not affiliated any more, they should not be allowed to talk
3403 // to each other.
3404 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3405 MoreAsserts.assertEmpty(targetUsers);
3406
3407 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3408 targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3409 MoreAsserts.assertEmpty(targetUsers);
Tony Mak2f26b792016-11-28 17:54:51 +00003410 }
3411
3412 public void testGetBindDeviceAdminTargetUsers_differentPackage() throws Exception {
3413 // Setup a device owner.
3414 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3415 setupDeviceOwner();
3416
3417 // Set up a managed profile managed by different package.
3418 final int MANAGED_PROFILE_USER_ID = 15;
3419 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3420 final ComponentName adminDifferentPackage =
3421 new ComponentName("another.package", "whatever.class");
3422 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3423
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003424 // Setting affiliation ids
3425 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3426 dpm.setAffiliationIds(admin1, userAffiliationIds);
3427
3428 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3429 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3430
Tony Mak2f26b792016-11-28 17:54:51 +00003431 // Calling from device owner admin, we should get zero bind device admin target users as
3432 // their packages are different.
Nicolas Prevotd5b03602016-12-06 13:32:22 +00003433 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
Tony Mak2f26b792016-11-28 17:54:51 +00003434 List<UserHandle> targetUsers = dpm.getBindDeviceAdminTargetUsers(admin1);
3435 MoreAsserts.assertEmpty(targetUsers);
3436
3437 // Calling from managed profile admin, we should still get zero target users for the same
3438 // reason.
3439 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3440 targetUsers = dpm.getBindDeviceAdminTargetUsers(adminDifferentPackage);
3441 MoreAsserts.assertEmpty(targetUsers);
3442 }
3443
Esteban Talaverabdcada92017-02-01 14:20:06 +00003444 public void testLockTaskPackagesAllowedForAffiliatedUsers() throws Exception {
3445 // Setup a device owner.
3446 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3447 setupDeviceOwner();
3448 // Lock task packages are updated when loading user data.
3449 verify(mContext.iactivityManager)
3450 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(new String[0]));
3451
3452 // Set up a managed profile managed by different package (package name shouldn't matter)
3453 final int MANAGED_PROFILE_USER_ID = 15;
3454 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 20456);
3455 final ComponentName adminDifferentPackage =
3456 new ComponentName("another.package", "whatever.class");
3457 addManagedProfile(adminDifferentPackage, MANAGED_PROFILE_ADMIN_UID, admin2);
3458 verify(mContext.iactivityManager)
3459 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3460
3461 // The DO can still set lock task packages
3462 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3463 final String[] doPackages = {"doPackage1", "doPackage2"};
3464 dpm.setLockTaskPackages(admin1, doPackages);
3465 MoreAsserts.assertEquals(doPackages, dpm.getLockTaskPackages(admin1));
3466 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3467 assertFalse(dpm.isLockTaskPermitted("anotherPackage"));
3468 verify(mContext.iactivityManager)
3469 .updateLockTaskPackages(eq(UserHandle.USER_SYSTEM), eq(doPackages));
3470
3471 // Managed profile is unaffiliated - shouldn't be able to setLockTaskPackages.
3472 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3473 final String[] poPackages = {"poPackage1", "poPackage2"};
3474 try {
3475 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3476 fail("Didn't throw expected security exception.");
3477 } catch (SecurityException expected) {
3478 }
3479 try {
3480 dpm.getLockTaskPackages(adminDifferentPackage);
3481 fail("Didn't throw expected security exception.");
3482 } catch (SecurityException expected) {
3483 }
3484 assertFalse(dpm.isLockTaskPermitted("doPackage1"));
3485
3486 // Setting same affiliation ids
3487 final List<String> userAffiliationIds = Arrays.asList("some-affiliation-id");
3488 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3489 dpm.setAffiliationIds(admin1, userAffiliationIds);
3490
3491 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3492 dpm.setAffiliationIds(adminDifferentPackage, userAffiliationIds);
3493
3494 // Now the managed profile can set lock task packages.
3495 dpm.setLockTaskPackages(adminDifferentPackage, poPackages);
3496 MoreAsserts.assertEquals(poPackages, dpm.getLockTaskPackages(adminDifferentPackage));
3497 assertTrue(dpm.isLockTaskPermitted("poPackage1"));
3498 assertFalse(dpm.isLockTaskPermitted("doPackage2"));
3499 verify(mContext.iactivityManager)
3500 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(poPackages));
3501
3502 // Unaffiliate the profile, lock task mode no longer available on the profile.
3503 dpm.setAffiliationIds(adminDifferentPackage, Collections.<String>emptyList());
3504 assertFalse(dpm.isLockTaskPermitted("poPackage1"));
3505 // Lock task packages cleared when loading user data and when the user becomes unaffiliated.
3506 verify(mContext.iactivityManager, times(2))
3507 .updateLockTaskPackages(eq(MANAGED_PROFILE_USER_ID), eq(new String[0]));
3508
3509 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3510 assertTrue(dpm.isLockTaskPermitted("doPackage1"));
3511 }
3512
Bartosz Fabianowskidd7f8da2016-11-30 11:09:22 +01003513 public void testIsDeviceManaged() throws Exception {
3514 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3515 setupDeviceOwner();
3516
3517 // The device owner itself, any uid holding MANAGE_USERS permission and the system can
3518 // find out that the device has a device owner.
3519 assertTrue(dpm.isDeviceManaged());
3520 mContext.binder.callingUid = 1234567;
3521 mContext.callerPermissions.add(permission.MANAGE_USERS);
3522 assertTrue(dpm.isDeviceManaged());
3523 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3524 mContext.binder.clearCallingIdentity();
3525 assertTrue(dpm.isDeviceManaged());
3526
3527 clearDeviceOwner();
3528
3529 // Any uid holding MANAGE_USERS permission and the system can find out that the device does
3530 // not have a device owner.
3531 mContext.binder.callingUid = 1234567;
3532 mContext.callerPermissions.add(permission.MANAGE_USERS);
3533 assertFalse(dpm.isDeviceManaged());
3534 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3535 mContext.binder.clearCallingIdentity();
3536 assertFalse(dpm.isDeviceManaged());
3537 }
3538
Bartosz Fabianowski365a3db2016-11-30 18:28:10 +01003539 public void testDeviceOwnerOrganizationName() throws Exception {
3540 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3541 setupDeviceOwner();
3542
3543 dpm.setOrganizationName(admin1, "organization");
3544
3545 // Device owner can retrieve organization managing the device.
3546 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3547
3548 // Any uid holding MANAGE_USERS permission can retrieve organization managing the device.
3549 mContext.binder.callingUid = 1234567;
3550 mContext.callerPermissions.add(permission.MANAGE_USERS);
3551 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3552 mContext.callerPermissions.remove(permission.MANAGE_USERS);
3553
3554 // System can retrieve organization managing the device.
3555 mContext.binder.clearCallingIdentity();
3556 assertEquals("organization", dpm.getDeviceOwnerOrganizationName());
3557
3558 // Removing the device owner clears the organization managing the device.
3559 clearDeviceOwner();
3560 assertNull(dpm.getDeviceOwnerOrganizationName());
3561 }
3562
Nicolas Prevotc9c1b2f2017-01-12 10:52:50 +00003563 public void testWipeDataManagedProfile() throws Exception {
3564 final int MANAGED_PROFILE_USER_ID = 15;
3565 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3566 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3567 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3568
3569 // Even if the caller is the managed profile, the current user is the user 0
3570 when(mContext.iactivityManager.getCurrentUser())
3571 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3572
3573 dpm.wipeData(0);
3574 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3575 MANAGED_PROFILE_USER_ID);
3576 }
3577
3578 public void testWipeDataManagedProfileDisallowed() throws Exception {
3579 final int MANAGED_PROFILE_USER_ID = 15;
3580 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3581 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3582
3583 // Even if the caller is the managed profile, the current user is the user 0
3584 when(mContext.iactivityManager.getCurrentUser())
3585 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3586
3587 when(mContext.userManager.getUserRestrictionSource(
3588 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3589 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3590 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3591 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3592 try {
3593 // The PO is not allowed to remove the profile if the user restriction was set on the
3594 // profile by the system
3595 dpm.wipeData(0);
3596 fail("SecurityException not thrown");
3597 } catch (SecurityException expected) {
3598 }
3599 }
3600
Esteban Talaverab88f42b2017-01-24 16:47:16 +00003601 public void testWipeDataDeviceOwner() throws Exception {
3602 setDeviceOwner();
3603 when(mContext.userManager.getUserRestrictionSource(
3604 UserManager.DISALLOW_FACTORY_RESET,
3605 UserHandle.SYSTEM))
3606 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3607
3608 dpm.wipeData(0);
3609 verify(mContext.recoverySystem).rebootWipeUserData(
3610 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3611 }
3612
3613 public void testWipeDataDeviceOwnerDisallowed() throws Exception {
3614 setDeviceOwner();
3615 when(mContext.userManager.getUserRestrictionSource(
3616 UserManager.DISALLOW_FACTORY_RESET,
3617 UserHandle.SYSTEM))
3618 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3619 try {
3620 // The DO is not allowed to wipe the device if the user restriction was set
3621 // by the system
3622 dpm.wipeData(0);
3623 fail("SecurityException not thrown");
3624 } catch (SecurityException expected) {
3625 }
3626 }
3627
3628 public void testMaximumFailedPasswordAttemptsReachedManagedProfile() throws Exception {
3629 final int MANAGED_PROFILE_USER_ID = 15;
3630 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3631 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3632
3633 // Even if the caller is the managed profile, the current user is the user 0
3634 when(mContext.iactivityManager.getCurrentUser())
3635 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3636
3637 when(mContext.userManager.getUserRestrictionSource(
3638 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3639 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3640 .thenReturn(UserManager.RESTRICTION_SOURCE_PROFILE_OWNER);
3641
3642 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3643 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3644
3645 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3646 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3647 // Failed password attempts on the parent user are taken into account, as there isn't a
3648 // separate work challenge.
3649 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3650 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3651 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3652
3653 // The profile should be wiped even if DISALLOW_REMOVE_MANAGED_PROFILE is enabled, because
3654 // both the user restriction and the policy were set by the PO.
3655 verify(mContext.userManagerInternal).removeUserEvenWhenDisallowed(
3656 MANAGED_PROFILE_USER_ID);
3657 verifyZeroInteractions(mContext.recoverySystem);
3658 }
3659
3660 public void testMaximumFailedPasswordAttemptsReachedManagedProfileDisallowed()
3661 throws Exception {
3662 final int MANAGED_PROFILE_USER_ID = 15;
3663 final int MANAGED_PROFILE_ADMIN_UID = UserHandle.getUid(MANAGED_PROFILE_USER_ID, 19436);
3664 addManagedProfile(admin1, MANAGED_PROFILE_ADMIN_UID, admin1);
3665
3666 // Even if the caller is the managed profile, the current user is the user 0
3667 when(mContext.iactivityManager.getCurrentUser())
3668 .thenReturn(new UserInfo(UserHandle.USER_SYSTEM, "user system", 0));
3669
3670 when(mContext.userManager.getUserRestrictionSource(
3671 UserManager.DISALLOW_REMOVE_MANAGED_PROFILE,
3672 UserHandle.of(MANAGED_PROFILE_USER_ID)))
3673 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3674
3675 mContext.binder.callingUid = MANAGED_PROFILE_ADMIN_UID;
3676 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3677
3678 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3679 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3680 // Failed password attempts on the parent user are taken into account, as there isn't a
3681 // separate work challenge.
3682 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3683 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3684 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3685
3686 // DISALLOW_REMOVE_MANAGED_PROFILE was set by the system, not the PO, so the profile is
3687 // not wiped.
3688 verify(mContext.userManagerInternal, never())
3689 .removeUserEvenWhenDisallowed(anyInt());
3690 verifyZeroInteractions(mContext.recoverySystem);
3691 }
3692
3693 public void testMaximumFailedPasswordAttemptsReachedDeviceOwner() throws Exception {
3694 setDeviceOwner();
3695 when(mContext.userManager.getUserRestrictionSource(
3696 UserManager.DISALLOW_FACTORY_RESET,
3697 UserHandle.SYSTEM))
3698 .thenReturn(UserManager.RESTRICTION_SOURCE_DEVICE_OWNER);
3699
3700 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3701
3702 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3703 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3704 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3705 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3706 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3707
3708 // The device should be wiped even if DISALLOW_FACTORY_RESET is enabled, because both the
3709 // user restriction and the policy were set by the DO.
3710 verify(mContext.recoverySystem).rebootWipeUserData(
3711 /*shutdown=*/ eq(false), anyString(), /*force=*/ eq(true));
3712 }
3713
3714 public void testMaximumFailedPasswordAttemptsReachedDeviceOwnerDisallowed() throws Exception {
3715 setDeviceOwner();
3716 when(mContext.userManager.getUserRestrictionSource(
3717 UserManager.DISALLOW_FACTORY_RESET,
3718 UserHandle.SYSTEM))
3719 .thenReturn(UserManager.RESTRICTION_SOURCE_SYSTEM);
3720
3721 dpm.setMaximumFailedPasswordsForWipe(admin1, 3);
3722
3723 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
3724 mContext.callerPermissions.add(permission.BIND_DEVICE_ADMIN);
3725 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3726 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3727 dpm.reportFailedPasswordAttempt(UserHandle.USER_SYSTEM);
3728
3729 // DISALLOW_FACTORY_RESET was set by the system, not the DO, so the device is not wiped.
3730 verifyZeroInteractions(mContext.recoverySystem);
3731 verify(mContext.userManagerInternal, never())
3732 .removeUserEvenWhenDisallowed(anyInt());
3733 }
3734
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003735 public void testGetPermissionGrantState() throws Exception {
3736 final String permission = "some.permission";
3737 final String app1 = "com.example.app1";
3738 final String app2 = "com.example.app2";
3739
3740 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app1), anyInt()))
3741 .thenReturn(PackageManager.PERMISSION_GRANTED);
3742 doReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED).when(mContext.packageManager)
3743 .getPermissionFlags(permission, app1, UserHandle.SYSTEM);
3744 when(mContext.packageManager.getPermissionFlags(permission, app1,
3745 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE)))
3746 .thenReturn(PackageManager.FLAG_PERMISSION_POLICY_FIXED);
3747 when(mContext.ipackageManager.checkPermission(eq(permission), eq(app2), anyInt()))
3748 .thenReturn(PackageManager.PERMISSION_DENIED);
3749 doReturn(0).when(mContext.packageManager).getPermissionFlags(permission, app2,
3750 UserHandle.SYSTEM);
3751 when(mContext.packageManager.getPermissionFlags(permission, app2,
3752 UserHandle.of(DpmMockContext.CALLER_USER_HANDLE))).thenReturn(0);
3753
3754 // System can retrieve permission grant state.
3755 mContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003756 mContext.packageName = "com.example.system";
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003757 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3758 dpm.getPermissionGrantState(null, app1, permission));
3759 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3760 dpm.getPermissionGrantState(null, app2, permission));
3761
3762 // A regular app cannot retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003763 mContext.binder.callingUid = setupPackageInPackageManager(app1, 1);
3764 mContext.packageName = app1;
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003765 try {
3766 dpm.getPermissionGrantState(null, app1, permission);
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003767 fail("Didn't throw SecurityException");
3768 } catch (SecurityException expected) {
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003769 }
3770
3771 // Profile owner can retrieve permission grant state.
Bartosz Fabianowski2dbf9ae2017-01-27 14:47:17 +01003772 mContext.binder.callingUid = DpmMockContext.CALLER_UID;
3773 mContext.packageName = admin1.getPackageName();
Bartosz Fabianowski4b0624f2017-01-16 11:47:28 +01003774 setAsProfileOwner(admin1);
3775 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_GRANTED,
3776 dpm.getPermissionGrantState(admin1, app1, permission));
3777 assertEquals(DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT,
3778 dpm.getPermissionGrantState(admin1, app2, permission));
3779 }
3780
Rubin Xuaab7a412016-12-30 21:13:29 +00003781 public void testResetPasswordWithToken() throws Exception {
3782 mContext.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3783 setupDeviceOwner();
3784 // test token validation
3785 try {
3786 dpm.setResetPasswordToken(admin1, new byte[31]);
3787 fail("should not have accepted tokens too short");
3788 } catch (IllegalArgumentException expected) {
3789 }
3790 // test adding a token
3791 final byte[] token = new byte[32];
3792 final long handle = 123456;
3793 final String password = "password";
3794 when(mContext.lockPatternUtils.addEscrowToken(eq(token), eq(UserHandle.USER_SYSTEM)))
3795 .thenReturn(handle);
3796 assertTrue(dpm.setResetPasswordToken(admin1, token));
3797
3798 // test password activation
3799 when(mContext.lockPatternUtils.isEscrowTokenActive(eq(handle), eq(UserHandle.USER_SYSTEM)))
3800 .thenReturn(true);
3801 assertTrue(dpm.isResetPasswordTokenActive(admin1));
3802
3803 // test reset password with token
3804 when(mContext.lockPatternUtils.setLockCredentialWithToken(eq(password),
3805 eq(LockPatternUtils.CREDENTIAL_TYPE_PASSWORD), eq(handle), eq(token),
3806 eq(UserHandle.USER_SYSTEM)))
3807 .thenReturn(true);
3808 assertTrue(dpm.resetPasswordWithToken(admin1, password, token, 0));
3809
3810 // test removing a token
3811 when(mContext.lockPatternUtils.removeEscrowToken(eq(handle), eq(UserHandle.USER_SYSTEM)))
3812 .thenReturn(true);
3813 assertTrue(dpm.clearResetPasswordToken(admin1));
3814 }
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003815
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003816 public void testIsCurrentInputMethodSetByOwnerForDeviceOwner() throws Exception {
3817 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3818 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3819 final int deviceOwnerUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3820 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3821 DpmMockContext.SYSTEM_UID);
3822 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3823 DpmMockContext.SYSTEM_UID);
3824
3825 // Set up a device owner.
3826 mContext.binder.callingUid = deviceOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003827 setupDeviceOwner();
3828
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003829 // First and second user set IMEs manually.
3830 mContext.binder.callingUid = firstUserSystemUid;
3831 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3832 mContext.binder.callingUid = secondUserSystemUid;
3833 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003834
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003835 // Device owner changes IME for first user.
3836 mContext.binder.callingUid = deviceOwnerUid;
3837 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003838 .thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003839 dpm.setSecureSetting(admin1, currentIme, "ime2");
3840 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003841 UserHandle.USER_SYSTEM);
3842 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003843 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3844 mContext.binder.callingUid = firstUserSystemUid;
3845 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3846 mContext.binder.callingUid = secondUserSystemUid;
3847 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003848
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003849 // Second user changes IME manually.
3850 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3851 mContext.binder.callingUid = firstUserSystemUid;
3852 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3853 mContext.binder.callingUid = secondUserSystemUid;
3854 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003855
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003856 // First user changes IME manually.
3857 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3858 mContext.binder.callingUid = firstUserSystemUid;
3859 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3860 mContext.binder.callingUid = secondUserSystemUid;
3861 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003862
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003863 // Device owner changes IME for first user again.
3864 mContext.binder.callingUid = deviceOwnerUid;
3865 when(mContext.settings.settingsSecureGetStringForUser(currentIme, UserHandle.USER_SYSTEM))
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003866 .thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003867 dpm.setSecureSetting(admin1, currentIme, "ime3");
3868 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003869 UserHandle.USER_SYSTEM);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003870 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3871 mContext.binder.callingUid = firstUserSystemUid;
3872 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3873 mContext.binder.callingUid = secondUserSystemUid;
3874 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003875
3876 // Restarting the DPMS should not lose information.
3877 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003878 mContext.binder.callingUid = firstUserSystemUid;
3879 assertTrue(dpm.isCurrentInputMethodSetByOwner());
3880 mContext.binder.callingUid = secondUserSystemUid;
3881 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003882
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003883 // Device owner can find out whether it set the current IME itself.
3884 mContext.binder.callingUid = deviceOwnerUid;
3885 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003886
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003887 // Removing the device owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003888 clearDeviceOwner();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003889 mContext.binder.callingUid = firstUserSystemUid;
3890 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3891 mContext.binder.callingUid = secondUserSystemUid;
3892 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003893 }
3894
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003895 public void testIsCurrentInputMethodSetByOwnerForProfileOwner() throws Exception {
3896 final String currentIme = Settings.Secure.DEFAULT_INPUT_METHOD;
3897 final Uri currentImeUri = Settings.Secure.getUriFor(currentIme);
3898 final int profileOwnerUid = DpmMockContext.CALLER_UID;
3899 final int firstUserSystemUid = UserHandle.getUid(UserHandle.USER_SYSTEM,
3900 DpmMockContext.SYSTEM_UID);
3901 final int secondUserSystemUid = UserHandle.getUid(DpmMockContext.CALLER_USER_HANDLE,
3902 DpmMockContext.SYSTEM_UID);
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003903
3904 // Set up a profile owner.
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003905 mContext.binder.callingUid = profileOwnerUid;
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003906 setupProfileOwner();
3907
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003908 // First and second user set IMEs manually.
3909 mContext.binder.callingUid = firstUserSystemUid;
3910 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3911 mContext.binder.callingUid = secondUserSystemUid;
3912 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003913
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003914 // Profile owner changes IME for second user.
3915 mContext.binder.callingUid = profileOwnerUid;
3916 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003917 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime1");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003918 dpm.setSecureSetting(admin1, currentIme, "ime2");
3919 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime2",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003920 DpmMockContext.CALLER_USER_HANDLE);
3921 reset(mContext.settings);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003922 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3923 mContext.binder.callingUid = firstUserSystemUid;
3924 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3925 mContext.binder.callingUid = secondUserSystemUid;
3926 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003927
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003928 // First user changes IME manually.
3929 dpms.notifyChangeToContentObserver(currentImeUri, UserHandle.USER_SYSTEM);
3930 mContext.binder.callingUid = firstUserSystemUid;
3931 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3932 mContext.binder.callingUid = secondUserSystemUid;
3933 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003934
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003935 // Second user changes IME manually.
3936 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3937 mContext.binder.callingUid = firstUserSystemUid;
3938 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3939 mContext.binder.callingUid = secondUserSystemUid;
3940 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003941
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003942 // Profile owner changes IME for second user again.
3943 mContext.binder.callingUid = profileOwnerUid;
3944 when(mContext.settings.settingsSecureGetStringForUser(currentIme,
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003945 DpmMockContext.CALLER_USER_HANDLE)).thenReturn("ime2");
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003946 dpm.setSecureSetting(admin1, currentIme, "ime3");
3947 verify(mContext.settings).settingsSecurePutStringForUser(currentIme, "ime3",
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003948 DpmMockContext.CALLER_USER_HANDLE);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003949 dpms.notifyChangeToContentObserver(currentImeUri, DpmMockContext.CALLER_USER_HANDLE);
3950 mContext.binder.callingUid = firstUserSystemUid;
3951 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3952 mContext.binder.callingUid = secondUserSystemUid;
3953 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003954
3955 // Restarting the DPMS should not lose information.
3956 initializeDpms();
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003957 mContext.binder.callingUid = firstUserSystemUid;
3958 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3959 mContext.binder.callingUid = secondUserSystemUid;
3960 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003961
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003962 // Profile owner can find out whether it set the current IME itself.
3963 mContext.binder.callingUid = profileOwnerUid;
3964 assertTrue(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003965
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003966 // Removing the profile owner should clear the information that it set the current IME.
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003967 dpm.clearProfileOwner(admin1);
Bartosz Fabianowski172f7802017-03-06 12:07:57 +01003968 mContext.binder.callingUid = firstUserSystemUid;
3969 assertFalse(dpm.isCurrentInputMethodSetByOwner());
3970 mContext.binder.callingUid = secondUserSystemUid;
3971 assertFalse(dpm.isCurrentInputMethodSetByOwner());
Bartosz Fabianowskiaff5e9c2017-01-25 06:09:13 +01003972 }
Rubin Xuaab7a412016-12-30 21:13:29 +00003973
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003974 public void testGetOwnerInstalledCaCertsForDeviceOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003975 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003976 setDeviceOwner();
3977
Robin Lee2c68dad2017-03-17 12:50:24 +00003978 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
3979 caller.packageName = admin1.getPackageName();
3980 caller.binder.callingUid = DpmMockContext.CALLER_SYSTEM_USER_UID;
3981
3982 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003983 }
3984
3985 public void testGetOwnerInstalledCaCertsForProfileOwner() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003986 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003987 setAsProfileOwner(admin1);
3988
Robin Lee2c68dad2017-03-17 12:50:24 +00003989 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
3990 caller.packageName = admin1.getPackageName();
3991 caller.binder.callingUid = DpmMockContext.CALLER_UID;
3992
3993 verifyCanGetOwnerInstalledCaCerts(admin1, caller);
3994 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(admin1, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003995 }
3996
3997 public void testGetOwnerInstalledCaCertsForDelegate() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00003998 mContext.packageName = mRealTestContext.getPackageName();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01003999 setAsProfileOwner(admin1);
4000
4001 final String delegate = "com.example.delegate";
4002 final int delegateUid = setupPackageInPackageManager(delegate, 20988);
4003 dpm.setCertInstallerPackage(admin1, delegate);
4004
Robin Lee2c68dad2017-03-17 12:50:24 +00004005 final DpmMockContext caller = new DpmMockContext(mRealTestContext, "test-caller");
4006 caller.packageName = delegate;
4007 caller.binder.callingUid = delegateUid;
4008
4009 verifyCanGetOwnerInstalledCaCerts(null, caller);
4010 verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(null, caller);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004011 }
4012
Robin Lee2c68dad2017-03-17 12:50:24 +00004013 private void verifyCanGetOwnerInstalledCaCerts(
4014 final ComponentName caller, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004015 final String alias = "cert";
4016 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004017
4018 // device admin (used for posting the tls notification)
4019 final DpmMockContext admin1Context;
4020 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4021 admin1Context = callerContext;
4022 } else {
4023 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4024 admin1Context.packageName = admin1.getPackageName();
4025 admin1Context.applicationInfo = new ApplicationInfo();
4026 }
4027 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4028
4029 // caller: device admin or delegated certificate installer
4030 callerContext.applicationInfo = new ApplicationInfo();
4031 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4032
4033 // system_server
4034 final DpmMockContext serviceContext = mContext;
4035 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4036 serviceContext.addPackageContext(callerUser, admin1Context);
4037 serviceContext.addPackageContext(callerUser, callerContext);
4038
4039 // Install a CA cert.
4040 runAsCaller(callerContext, dpms, (dpm) -> {
4041 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4042 .thenReturn(alias);
4043 assertTrue(dpm.installCaCert(caller, caCert));
4044 when(mContext.keyChainConnection.getService().getUserCaAliases())
4045 .thenReturn(asSlice(new String[] {alias}));
4046
4047 });
4048
4049 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4050 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004051 flushTasks();
4052
Robin Lee2c68dad2017-03-17 12:50:24 +00004053 final List<String> ownerInstalledCaCerts = new ArrayList<>();
4054
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004055 // Device Owner / Profile Owner can find out which CA certs were installed by itself.
Robin Lee2c68dad2017-03-17 12:50:24 +00004056 runAsCaller(admin1Context, dpms, (dpm) -> {
4057 final List<String> installedCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4058 assertEquals(Arrays.asList(alias), installedCaCerts);
4059 ownerInstalledCaCerts.addAll(installedCaCerts);
4060 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004061
4062 // Restarting the DPMS should not lose information.
4063 initializeDpms();
Robin Lee2c68dad2017-03-17 12:50:24 +00004064 runAsCaller(admin1Context, dpms, (dpm) -> {
4065 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
4066 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004067
4068 // System can find out which CA certs were installed by the Device Owner / Profile Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004069 runAsCaller(serviceContext, dpms, (dpm) -> {
4070 assertEquals(ownerInstalledCaCerts, dpm.getOwnerInstalledCaCerts(callerUser));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004071
Robin Lee2c68dad2017-03-17 12:50:24 +00004072 // Remove the CA cert.
4073 reset(mContext.keyChainConnection.getService());
4074 });
4075
4076 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4077 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004078 flushTasks();
4079
4080 // Verify that the CA cert is no longer reported as installed by the Device Owner / Profile
4081 // Owner.
Robin Lee2c68dad2017-03-17 12:50:24 +00004082 runAsCaller(admin1Context, dpms, (dpm) -> {
4083 MoreAsserts.assertEmpty(dpm.getOwnerInstalledCaCerts(callerUser));
4084 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004085 }
4086
Robin Lee2c68dad2017-03-17 12:50:24 +00004087 private void verifyCantGetOwnerInstalledCaCertsProfileOwnerRemoval(
4088 final ComponentName callerName, final DpmMockContext callerContext) throws Exception {
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004089 final String alias = "cert";
4090 final byte[] caCert = TEST_CA.getBytes();
Robin Lee2c68dad2017-03-17 12:50:24 +00004091
4092 // device admin (used for posting the tls notification)
4093 final DpmMockContext admin1Context;
4094 if (admin1.getPackageName().equals(callerContext.getPackageName())) {
4095 admin1Context = callerContext;
4096 } else {
4097 admin1Context = new DpmMockContext(mRealTestContext, "test-admin");
4098 admin1Context.packageName = admin1.getPackageName();
4099 admin1Context.applicationInfo = new ApplicationInfo();
4100 }
4101 when(admin1Context.resources.getColor(anyInt(), anyObject())).thenReturn(Color.WHITE);
4102
4103 // caller: device admin or delegated certificate installer
4104 callerContext.applicationInfo = new ApplicationInfo();
4105 final UserHandle callerUser = callerContext.binder.getCallingUserHandle();
4106
4107 // system_server
4108 final DpmMockContext serviceContext = mContext;
4109 serviceContext.binder.callingUid = DpmMockContext.SYSTEM_UID;
4110 serviceContext.addPackageContext(callerUser, admin1Context);
4111 serviceContext.addPackageContext(callerUser, callerContext);
4112
4113 // Install a CA cert as caller
4114 runAsCaller(callerContext, dpms, (dpm) -> {
4115 when(mContext.keyChainConnection.getService().installCaCertificate(caCert))
4116 .thenReturn(alias);
4117 assertTrue(dpm.installCaCert(callerName, caCert));
4118 });
4119
4120 // Fake the CA cert as having been installed
4121 when(serviceContext.keyChainConnection.getService().getUserCaAliases())
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004122 .thenReturn(asSlice(new String[] {alias}));
Robin Lee2c68dad2017-03-17 12:50:24 +00004123 serviceContext.injectBroadcast(new Intent(KeyChain.ACTION_TRUST_STORE_CHANGED)
4124 .putExtra(Intent.EXTRA_USER_HANDLE, callerUser.getIdentifier()));
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004125 flushTasks();
4126
Robin Lee2c68dad2017-03-17 12:50:24 +00004127 // Removing the Profile Owner should clear the information on which CA certs were installed
4128 runAsCaller(admin1Context, dpms, (dpm) -> {
4129 dpm.clearProfileOwner(admin1);
4130 });
4131
4132 runAsCaller(serviceContext, dpms, (dpm) -> {
4133 final List<String> ownerInstalledCaCerts = dpm.getOwnerInstalledCaCerts(callerUser);
4134 assertNotNull(ownerInstalledCaCerts);
4135 assertTrue(ownerInstalledCaCerts.isEmpty());
4136 });
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004137 }
4138
Victor Chang3e794af2016-03-04 13:48:17 +00004139 private void setUserSetupCompleteForUser(boolean isUserSetupComplete, int userhandle) {
4140 when(mContext.settings.settingsSecureGetIntForUser(Settings.Secure.USER_SETUP_COMPLETE, 0,
4141 userhandle)).thenReturn(isUserSetupComplete ? 1 : 0);
4142 dpms.notifyChangeToContentObserver(
4143 Settings.Secure.getUriFor(Settings.Secure.USER_SETUP_COMPLETE), userhandle);
4144 }
4145
4146 private void assertProvisioningAllowed(String action, boolean expected) {
4147 assertEquals("isProvisioningAllowed(" + action + ") returning unexpected result", expected,
4148 dpm.isProvisioningAllowed(action));
4149 }
Tony Mak2f26b792016-11-28 17:54:51 +00004150
Nicolas Prevot45d29072017-01-18 16:11:19 +00004151 private void assertProvisioningAllowed(String action, boolean expected, String packageName,
4152 int uid) {
4153 String previousPackageName = mContext.packageName;
4154 int previousUid = mMockContext.binder.callingUid;
4155
4156 // Call assertProvisioningAllowed with the packageName / uid passed as arguments.
4157 mContext.packageName = packageName;
4158 mMockContext.binder.callingUid = uid;
4159 assertProvisioningAllowed(action, expected);
4160
4161 // Set the previous package name / calling uid to go back to the initial state.
4162 mContext.packageName = previousPackageName;
4163 mMockContext.binder.callingUid = previousUid;
4164 }
4165
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004166 private void assertCheckProvisioningPreCondition(String action, int provisioningCondition) {
Esteban Talavera01576862016-12-15 11:16:44 +00004167 assertCheckProvisioningPreCondition(action, admin1.getPackageName(), provisioningCondition);
4168 }
4169
4170 private void assertCheckProvisioningPreCondition(
4171 String action, String packageName, int provisioningCondition) {
4172 assertEquals("checkProvisioningPreCondition("
4173 + action + ", " + packageName + ") returning unexpected result",
4174 provisioningCondition, dpm.checkProvisioningPreCondition(action, packageName));
Mahaver Chopra849fd6f2016-11-03 20:28:10 +00004175 }
4176
Tony Mak2f26b792016-11-28 17:54:51 +00004177 /**
4178 * Setup a managed profile with the specified admin and its uid.
4179 * @param admin ComponentName that's visible to the test code, which doesn't have to exist.
4180 * @param adminUid uid of the admin package.
4181 * @param copyFromAdmin package information for {@code admin} will be built based on this
4182 * component's information.
4183 */
4184 private void addManagedProfile(
4185 ComponentName admin, int adminUid, ComponentName copyFromAdmin) throws Exception {
4186 final int userId = UserHandle.getUserId(adminUid);
4187 mContext.addUser(userId, UserInfo.FLAG_MANAGED_PROFILE, UserHandle.USER_SYSTEM);
4188 mContext.callerPermissions.addAll(OWNER_SETUP_PERMISSIONS);
4189 setUpPackageManagerForFakeAdmin(admin, adminUid, copyFromAdmin);
4190 dpm.setActiveAdmin(admin, false, userId);
4191 assertTrue(dpm.setProfileOwner(admin, null, userId));
4192 mContext.callerPermissions.removeAll(OWNER_SETUP_PERMISSIONS);
4193 }
Robin Lee7f5c91c2017-02-08 21:27:02 +00004194
4195 /**
Robin Leeabaa0692017-02-20 20:54:22 +00004196 * Convert String[] to StringParceledListSlice.
Robin Lee7f5c91c2017-02-08 21:27:02 +00004197 */
Robin Leeabaa0692017-02-20 20:54:22 +00004198 private static StringParceledListSlice asSlice(String[] s) {
4199 return new StringParceledListSlice(Arrays.asList(s));
Robin Lee7f5c91c2017-02-08 21:27:02 +00004200 }
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004201
4202 private void flushTasks() throws Exception {
Robin Lee2c68dad2017-03-17 12:50:24 +00004203 dpms.mHandler.runWithScissors(() -> {}, 0 /*now*/);
4204 dpms.mBackgroundHandler.runWithScissors(() -> {}, 0 /*now*/);
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004205
Robin Lee2c68dad2017-03-17 12:50:24 +00004206 // We can't let exceptions happen on the background thread. Throw them here if they happen
4207 // so they still cause the test to fail despite being suppressed.
4208 mContext.rethrowBackgroundBroadcastExceptions();
Bartosz Fabianowski05dc9f72017-02-22 23:41:14 +01004209 }
Victor Chang3e794af2016-03-04 13:48:17 +00004210}